private void applyJsonToAuthorizable(URL url, Authorizable authorizable, Session session) throws IOException, RepositoryException { String jsonString = IOUtils.readFully(url.openStream(), "UTF-8"); if (jsonString != null) { Map<String, Object[]> postprocessParameters = new HashMap<String, Object[]>(); try { JSONObject jsonObject = new JSONObject(jsonString); Iterator<String> keys = jsonObject.keys(); while (keys.hasNext()) { String key = keys.next(); Object jsonValue = jsonObject.get(key); if (key.startsWith(SlingPostConstants.RP_PREFIX)) { postprocessParameters.put(key, new Object[] {jsonValue}); } else { Value value = JcrResourceUtil.createValue(jsonValue, session); authorizable.setProperty(key, value); } } } catch (JSONException e) { LOGGER.error("Faulty JSON at " + url, e); } try { authorizablePostProcessService.process( authorizable, session, ModificationType.CREATE, postprocessParameters); } catch (Exception e) { LOGGER.error("Could not configure default authorizable " + authorizable.getID(), e); } } }
/** @throws JSONException */ private void assertFileNodeInfo(JSONObject j) throws JSONException { assertEquals("/path/to/file.doc", j.getString("jcr:path")); assertEquals("file.doc", j.getString("jcr:name")); assertEquals("bar", j.getString("foo")); assertEquals("text/plain", j.getString("jcr:mimeType")); assertEquals(12345, j.getLong("jcr:data")); }
@Override protected final void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); final JSONArray jsonArray = new JSONArray(); try { for (Map.Entry<String, TagDataConverter> entry : this.tagDataConverters.entrySet()) { final JSONObject jsonObject = new JSONObject(); jsonObject.put("label", entry.getValue().getLabel()); jsonObject.put("value", entry.getKey()); jsonArray.put(jsonObject); } response.getWriter().print(jsonArray.toString()); } catch (JSONException e) { response.setStatus(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR); } }
/** * Extract the value of a MultiFieldPanel property into a list of maps. Will never return a null * map, but may return an empty one. Invalid property values are logged and skipped. * * @param resource the resource * @param name the property name * @return a list of maps. */ @Function public static List<Map<String, String>> getMultiFieldPanelValues(Resource resource, String name) { ValueMap map = resource.adaptTo(ValueMap.class); List<Map<String, String>> results = new ArrayList<Map<String, String>>(); if (map.containsKey(name)) { String[] values = map.get(name, new String[0]); for (String value : values) { try { JSONObject parsed = new JSONObject(value); Map<String, String> columnMap = new HashMap<String, String>(); for (Iterator<String> iter = parsed.keys(); iter.hasNext(); ) { String key = iter.next(); String innerValue = parsed.getString(key); columnMap.put(key, innerValue); } results.add(columnMap); } catch (JSONException e) { log.error( String.format("Unable to parse JSON in %s property of %s", name, resource.getPath()), e); } } } return results; }
@Override protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { final Session session = createAdminSession(); try { String statusFilter = req.getParameter("status"); if (statusFilter == null) { // By default, only approved posts are returned. statusFilter = RelatedUgcNodeIndexerExtension.FIELD_STATE_APPROVED; } final List<Post> mltPosts = RelatedSearchUtil.getRelatedPosts( getResourceResolver(session), req.getParameter("q"), statusFilter, req.getParameter("resource-type"), req.getParameter("component-path"), MLT_FIELDS, Integer.valueOf(req.getParameter("max-results")), MIN_TERM_FREQ, MIN_DOC_FREQ); if (mltPosts == null) { return; } final JSONObject json = new JSONObject(); JSONObject match; final List<JSONObject> matches = new ArrayList<JSONObject>(); for (final Post p : mltPosts) { match = new JSONObject(); match.put("subject", xssProtectionService.protectFromXSS(p.getSubject())); match.put("replyCount", p.getRepliesCount()); match.put("url", p.getUrl()); match.put("id", p.getId()); match.put("created", p.getCreated()); match.put("createdBy", xssProtectionService.protectFromXSS(p.getCreatedBy().getFullName())); matches.add(match); } json.put("mlt", matches); resp.setContentType("application/json"); resp.getWriter().write(json.toString()); } catch (final Exception e) { throw new ServletException(e); } finally { if (session != null) { session.logout(); } } }
/** Access contentfinder below /content */ @Test public void testContentView() throws JSONException, ClientException { RequestExecutor exec = authorAuthor.http.doGet(CONTENTFINDER_ASSET_VIEW + "/content", 200); // verify via hits length JSONObject searchResultJson = new JSONObject(exec.getContent()); JSONArray hits = searchResultJson.getJSONArray("hits"); Assert.assertTrue("No hits found for search with query 'geometrixx'", hits.length() > 0); }
/** * Produce a comma delimited text from a JSONArray of JSONObjects. The first row will be a list of * names obtained by inspecting the first JSONObject. * * @param ja A JSONArray of JSONObjects. * @return A comma delimited text. * @throws JSONException */ public static String toString(JSONArray ja) throws JSONException { JSONObject jo = ja.optJSONObject(0); if (jo != null) { JSONArray names = jo.names(); if (names != null) { return rowToString(names) + toString(names, ja); } } return null; }
/** list collection from user home in JSONArray */ private JSONArray list(SlingHttpServletRequest request, SlingHttpServletResponse response) throws RepositoryException, JSONException { final Session userSession = request.getResourceResolver().adaptTo(Session.class); Node collHome = getCollectionHome(userSession); List<JSONObject> jsonObjList = new ArrayList<JSONObject>(); NodeIterator itr = collHome.getNodes(); while (itr.hasNext()) { JSONObject jsonObject = new JSONObject(); jsonObject.put(PATH, itr.nextNode().getPath()); jsonObjList.add(jsonObject); } return new JSONArray(jsonObjList); }
/** * Produce a comma delimited text from a JSONArray of JSONObjects using a provided list of names. * The list of names is not included in the output. * * @param names A JSONArray of strings. * @param ja A JSONArray of JSONObjects. * @return A comma delimited text. * @throws JSONException */ public static String toString(JSONArray names, JSONArray ja) throws JSONException { if (names == null || names.length() == 0) { return null; } StringBuffer sb = new StringBuffer(); for (int i = 0; i < ja.length(); i += 1) { JSONObject jo = ja.optJSONObject(i); if (jo != null) { sb.append(rowToString(jo.toJSONArray(names))); } } return sb.toString(); }
/** * creates empty collection under ~user-home/collection. If collection with same name exists, it * throws exception */ @Override protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException { try { JSONObject jsonObject = create(request, response); response.setContentType(CONTENT_TYPE_JSON); response.setCharacterEncoding(ENCODING_UTF8); response.setStatus(SlingHttpServletResponse.SC_CREATED); response.getWriter().write(jsonObject.toString()); } catch (Exception e) { log.error("Error in create collection: " + e.getMessage(), e); throw new ServletException(e); } }
private JSONArray searchPagesForTag(String tagID) throws ClientException, JSONException { String query = "tag:\"" + tagID + "\""; // built the URL parameters URLParameterBuilder params = new URLParameterBuilder(); params.add(new BasicNameValuePair("query", query)); params.add(new BasicNameValuePair("type", "cq:Page")); params.add(new BasicNameValuePair("_charset", "utf-8")); RequestExecutor exec = authorAuthor.http.doGet(CONTENTFINDER_PAGE_VIEW + "/content", params, 200); // verify via hits length JSONObject searchResultJson = new JSONObject(exec.getContent()); return searchResultJson.getJSONArray("hits"); }
/** * Constructor by value. * * @param name * @param title * @param number * @param resolutionWidth * @param resolutionHeight * @param folioProperties * @throws DPSException * @throws JSONException */ public FolioImpl( String name, String title, String number, int resolutionWidth, int resolutionHeight, Map<String, DPSValue> folioProperties) throws DPSException, JSONException { this(folioProperties); data.put(FolioProperty.NAME.getName(), getSafeName(name)); data.put(FolioProperty.TITLE.getName(), title); data.put(FolioProperty.NUMBER.getName(), number); data.put(FolioProperty.RESOLUTION_WIDTH.getName(), String.valueOf(resolutionWidth)); data.put(FolioProperty.RESOLUTION_HEIGHT.getName(), String.valueOf(resolutionHeight)); }
private void addMessage(JSONObject jsonObject, String message) { try { jsonObject.put("message", message); } catch (JSONException e) { log.error("Could not formulate JSON Response", e); } }
@Test public void testWriteSiteInfo() throws JSONException, RepositoryException, IOException { Node siteNode = new MockNode("/sites/foo"); SiteService siteService = mock(SiteService.class); when(siteService.getMemberCount(siteNode)).thenReturn(11); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Writer w = new PrintWriter(baos); JSONWriter write = new JSONWriter(w); FileUtils.writeSiteInfo(siteNode, write, siteService); w.flush(); String s = baos.toString("UTF-8"); JSONObject o = new JSONObject(s); assertEquals("11", o.get("member-count")); assertEquals(siteNode.getPath(), o.get("jcr:path")); }
/** Seach images in contentfinder below /content/dam */ @Test public void testDamSearch() throws JSONException, ClientException { String query = ".jpg"; // built the URL parameters URLParameterBuilder params = new URLParameterBuilder(); params.add(new BasicNameValuePair("query", query)); params.add(new BasicNameValuePair("mimeType", "image")); params.add(new BasicNameValuePair("_charset", "utf-8")); RequestExecutor exec = authorAuthor.http.doGet(CONTENTFINDER_ASSET_VIEW + "/content/dam", params, 200); // verify via hits length JSONObject searchResultJson = new JSONObject(exec.getContent()); JSONArray hits = searchResultJson.getJSONArray("hits"); Assert.assertTrue("No hits found for search with query 'geometrixx'", hits.length() > 0); }
/** * creates empty collection. collection name is retrieved from request parameter * * @param request * @param response * @return * @throws ServletException * @throws IOException * @throws RepositoryException * @throws JSONException */ private JSONObject create(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException, RepositoryException, JSONException { final RequestParameter nameParam = request.getRequestParameter(REQ_PRM_COLL_NAME); final Session userSession = request.getResourceResolver().adaptTo(Session.class); JSONObject jsonObject = new JSONObject(); Node collHome = getCollectionHome(userSession); if (collHome.hasNode(nameParam.getString())) { throw new ServletException( "cannot create collection. '" + nameParam.getString() + "' already exists"); } else { Node coll = collHome.addNode(nameParam.getString(), JcrConstants.NT_UNSTRUCTURED); coll.setProperty("sling:resourceType", "cq/collections"); userSession.save(); jsonObject.put(PATH, coll.getPath()); } return jsonObject; }
@Override protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { response.setHeader("Content-Type", "application/json"); // response.getWriter().print("{\"coming\":\"soon\"}"); String[] keys = repository.getDescriptorKeys(); JSONObject jsonObj = new JSONObject(); for (String key : keys) { try { jsonObj.put(key, repository.getDescriptor(key)); } catch (JSONException e) { e.printStackTrace(); } } response.getWriter().print(jsonObj.toString()); }
public ArrayList<UtilModel> getLinkList() { ArrayList<UtilModel> values = new ArrayList<UtilModel>(); linkList = properties.get("list", new String[0]); // String[].class try { for (String temp : linkList) { JSONObject json = new JSONObject(temp); String link = json.getString("link"); String title = json.getString("title"); UtilModel utilModel = new UtilModel(); utilModel.setPropertyOne(link); utilModel.setPropertyTwo(title); values.add(utilModel); } } catch (JSONException e) { e.printStackTrace(); } return values; }
public ArrayList<UtilModel> getTitleList() { titleList = new ArrayList<UtilModel>(); String[] values = properties.get("list", new String[0]); try { for (String temp : values) { JSONObject json = new JSONObject(temp); String listLink = json.getString("listLink"); String title = json.getString("title"); UtilModel utilModel = new UtilModel(); utilModel.setPropertyOne(title); utilModel.setPropertyTwo(listLink); titleList.add(utilModel); } } catch (JSONException e) { e.printStackTrace(); } return titleList; }
private void migrateFollowUsImage( Element followUsEle, Node midSizeLowerRightNode, String locale, Map<String, String> urlMap) throws PathNotFoundException, RepositoryException, JSONException { if (followUsEle != null) { if (midSizeLowerRightNode.hasNode("followus")) { Node followUsNode = midSizeLowerRightNode.getNode("followus"); Element title = followUsEle.getElementsByTag("h2").first(); if (title != null) { followUsNode.setProperty("title", title.text()); } else { sb.append(Constants.FOLLOWUS_TITLE_NOT_FOUND); } Elements list = followUsEle.getElementsByTag("li"); if (list != null) { List<String> listAdd = new ArrayList<String>(); for (Element li : list) { Element a = li.getElementsByTag("a").first(); if (a != null) { String aURL = a.absUrl("href"); if (aURL.equals("")) { aURL = a.attr("href"); } aURL = FrameworkUtils.getLocaleReference(aURL, urlMap, locale, sb); JSONObject obj = new JSONObject(); obj.put("linktext", a.text()); obj.put("linkurl", aURL); obj.put("icon", li.className()); listAdd.add(obj.toString()); } else { sb.append(Constants.FOLLOW_US_ANCHOR_ELEMENT_NOT_FOUND); } } followUsNode.setProperty("links", listAdd.toArray(new String[listAdd.size()])); } else { sb.append(Constants.FOLLOW_US_ANCHOR_ELEMENT_NOT_FOUND); } } else { sb.append(Constants.FOLLOWUS_NODE_NOT_FOUND); } } else { sb.append(Constants.FOLLOWUS_ELEMENT_NOT_FOUND); } }
/** * Constructor by properties * * @param folioProperties * @throws DPSException * @throws JSONException */ public FolioImpl(Map<String, DPSValue> folioProperties) throws DPSException, JSONException { data = new JSONObject(); for (Map.Entry<String, DPSValue> entry : folioProperties.entrySet()) { switch (entry.getValue().getType()) { case DPSValue.BOOLEAN: data.put(entry.getKey(), entry.getValue().getString()); break; case DPSValue.DATE: data.put(entry.getKey(), getDateAsDPSString(entry.getValue().getDate().getTime())); break; case DPSValue.LONG: data.put(entry.getKey(), entry.getValue().getLong()); break; default: data.put(entry.getKey(), entry.getValue().getString()); break; } } }
// start setting of list in right rail public void rightRailList( Node listNode, Element rightListEle, Map<String, String> urlMap, String locale) { try { Element title; Element description; Elements headElements = rightListEle.getElementsByTag("h2"); if (headElements.size() > 1) { title = rightListEle.getElementsByTag("h2").last(); description = rightListEle.getElementsByTag("p").last(); sb.append("<li>Mismatch in count of list panel component in right rail.</li>"); } else { title = rightListEle.getElementsByTag("h2").first(); description = rightListEle.getElementsByTag("p").first(); } listNode.setProperty("title", title.text()); javax.jcr.Node introNode = listNode.getNode("intro"); introNode.setProperty("paragraph_rte", description.text()); javax.jcr.Node eleListNode = listNode.getNode("element_list_0"); Elements ulList = rightListEle.getElementsByTag("ul"); for (Element element : ulList) { java.util.List<String> list = new ArrayList<String>(); Elements menuLiList = element.getElementsByTag("li"); for (Element li : menuLiList) { JSONObject jsonObjrr = new JSONObject(); Element listItemAnchor = li.getElementsByTag("a").first(); String anchorText = listItemAnchor != null ? listItemAnchor.text() : ""; String anchorHref = listItemAnchor.absUrl("href"); if (StringUtil.isBlank(anchorHref)) { anchorHref = listItemAnchor.attr("href"); } // Start extracting valid href log.debug("Before right list LinkUrl" + anchorHref + "\n"); anchorHref = FrameworkUtils.getLocaleReference(anchorHref, urlMap, locale, sb); log.debug("after right list LinkUrl" + anchorHref + "\n"); // End extracting valid href jsonObjrr.put("linktext", anchorText); jsonObjrr.put("linkurl", anchorHref); jsonObjrr.put("icon", "none"); jsonObjrr.put("size", ""); jsonObjrr.put("description", ""); jsonObjrr.put("openInNewWindow", "false"); list.add(jsonObjrr.toString()); } eleListNode.setProperty("listitems", list.toArray(new String[list.size()])); } log.debug("Updated title, descriptoin and linktext at " + listNode.getPath()); } catch (Exception e) { e.printStackTrace(); } }
public ArrayList<UtilModel> getTitleLinkList() { ArrayList<UtilModel> valuesOne = new ArrayList<UtilModel>(); titleLinkList = properties.get("link", new String[0]); try { for (String tempOne : titleLinkList) { JSONObject jsonObj = new JSONObject(tempOne); String link = jsonObj.getString("link"); String site = jsonObj.getString("site"); UtilModel utilModel = new UtilModel(); utilModel.setPropertyOne(link); utilModel.setPropertyTwo(site); valuesOne.add(utilModel); } } catch (JSONException e) { e.printStackTrace(); } return valuesOne; }
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException { PrintWriter out = response.getWriter(); try { response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); String coffee = request.getParameter("coffee"); String sugar = request.getParameter("sugar"); String milk = request.getParameter("milk"); int coffee_price, sugar_price, milk_price, bill; JSONObject jsonObject = new JSONObject(); JSONArray jsonArray = new JSONArray(); if (coffee.equals("Latte")) { coffee_price = 150; } else if (coffee.equals("Cappuccino")) { coffee_price = 100; } else { coffee_price = 120; } if (sugar.equals("Sugar Free")) { sugar_price = 50; } else if (sugar.equals("Brown Sugar")) { sugar_price = 40; } else { sugar_price = 20; } if (milk.equals("Full Cream")) { milk_price = 50; } else if (milk.equals("Normal Milk")) { milk_price = 40; } else { milk_price = 30; } bill = coffee_price + sugar_price + milk_price; jsonObject.put("bill", bill); response.getWriter().write(jsonObject.toString()); } catch (Exception e) { } }
/** * @param queryNode * @param queryOptions * @return * @throws RepositoryException * @throws ValueFormatException * @throws PathNotFoundException * @throws JSONException */ private JSONObject accumulateQueryOptions(Node queryNode) throws RepositoryException, ValueFormatException, PathNotFoundException, JSONException { JSONObject queryOptions = null; if (queryNode.hasProperty(SAKAI_QUERY_TEMPLATE_OPTIONS)) { // process the options as JSON string String optionsProp = queryNode.getProperty(SAKAI_QUERY_TEMPLATE_OPTIONS).getString(); queryOptions = new JSONObject(optionsProp); } else if (queryNode.hasNode(SAKAI_QUERY_TEMPLATE_OPTIONS)) { // process the options as a sub-node Node optionsNode = queryNode.getNode(SAKAI_QUERY_TEMPLATE_OPTIONS); if (optionsNode.hasProperties()) { queryOptions = new JSONObject(); PropertyIterator props = optionsNode.getProperties(); while (props.hasNext()) { javax.jcr.Property prop = props.nextProperty(); if (!prop.getName().startsWith("jcr:")) { queryOptions.put(prop.getName(), prop.getString()); } } } } return queryOptions; }
/** * @param propertiesMap * @param queryOptions * @return * @throws JSONException * @throws MissingParameterException */ private Map<String, String> processOptions( Map<String, String> propertiesMap, JSONObject queryOptions) throws JSONException, MissingParameterException { Collection<String> missingTerms; Map<String, String> options = Maps.newHashMap(); if (queryOptions != null) { Iterator<String> keys = queryOptions.keys(); while (keys.hasNext()) { String key = keys.next(); String val = queryOptions.getString(key); missingTerms = templateService.missingTerms(propertiesMap, val); if (!missingTerms.isEmpty()) { throw new MissingParameterException( "Your request is missing parameters for the template: " + StringUtils.join(missingTerms, ", ")); } String processedVal = templateService.evaluateTemplate(propertiesMap, val); options.put(key, processedVal); } } return options; }
@Test public void testWriteLinkNode() throws JSONException, RepositoryException, IOException { Session session = mock(Session.class); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Writer w = new PrintWriter(baos); JSONWriter write = new JSONWriter(w); SiteService siteService = mock(SiteService.class); Node node = new MockNode("/path/to/link"); node.setProperty(FilesConstants.SAKAI_LINK, "uuid"); node.setProperty("foo", "bar"); Node fileNode = createFileNode(); when(session.getNodeByIdentifier("uuid")).thenReturn(fileNode); FileUtils.writeLinkNode(node, session, write, siteService); w.flush(); String s = baos.toString("UTF-8"); JSONObject j = new JSONObject(s); assertEquals("/path/to/link", j.getString("jcr:path")); assertEquals("bar", j.getString("foo")); assertFileNodeInfo(j.getJSONObject("file")); }
public void setForHero( Elements heroElements, Node heroPanelLarge, String locale, Map<String, String> urlMap) { try { Value[] panelPropertiest = null; Property panelNodesProperty = heroPanelLarge.hasProperty("panelNodes") ? heroPanelLarge.getProperty("panelNodes") : null; if (panelNodesProperty.isMultiple()) { panelPropertiest = panelNodesProperty.getValues(); } int i = 0; Node heroPanelNode = null; for (Element ele : heroElements) { if (panelPropertiest != null && i <= panelPropertiest.length) { String propertyVal = panelPropertiest[i].getString(); if (StringUtils.isNotBlank(propertyVal)) { JSONObject jsonObj = new JSONObject(propertyVal); if (jsonObj.has("panelnode")) { String panelNodeProperty = jsonObj.get("panelnode").toString(); heroPanelNode = heroPanelLarge.hasNode(panelNodeProperty) ? heroPanelLarge.getNode(panelNodeProperty) : null; } } i++; } else { sb.append("<li>No heropanel Node found.</li>"); } int imageSrcEmptyCount = 0; heroPanelTranslate(heroPanelNode, ele, locale, urlMap, imageSrcEmptyCount); } } catch (Exception e) { } }
@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); } }
@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); } }