/** @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")); }
/** * 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; }
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; }
@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 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; }
/** * @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 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()); }
public void execute(final WorkItem item, final WorkflowSession session, final MetaDataMap args) throws SocialModerationException { log.debug("In the workflow... (Flagged in JCR) "); try { validate(item); final JSONArray arr = new JSONArray((String) item.getWorkflowData().getPayload()); final ResourceResolver resolver = getResourceResolver(session.getSession()); for (int i = 0; i < arr.length(); i++) { final JSONObject obj = (JSONObject) arr.get(i); final String path = obj.getString(ModerationConstants.PATH); if (!obj.has(ModerationConstants.ACTION_FLAG)) { throw new SocialModerationException( FLAG_VERB_NOT_PRESENT_IN_PAYLOAD, ModerationConstants.ERR_FLAG_VERB_NOT_PRESENT_IN_PAYLOAD); } final boolean isFlagged = obj.getBoolean(ModerationConstants.ACTION_FLAG); final Resource resource = resolver.getResource(path); if (resource == null) { throw new SocialModerationException( ERR_SPECIFIED_RESOURCE_DOES_NOT_EXIST + path, ModerationConstants.ERR_SPECIFIED_RESOURCE_DOES_NOT_EXIST); } else { final Comment comment = resource.adaptTo(Comment.class); if (comment != null) { final Node node = resource.adaptTo(Node.class); node.setProperty(ModerationConstants.PROP_IS_FLAGGED, isFlagged); node.setProperty(ModerationConstants.PROP_IS_READ, true); addModHistory( profileMgr, resolver, node, ModerationConstants.PROP_IS_FLAGGED, String.valueOf(isFlagged), item.getWorkflow().getInitiator()); node.getSession().save(); replicator.replicate( session.getSession(), com.day.cq.replication.ReplicationActionType.ACTIVATE, path.substring(0, path.lastIndexOf('/')), null); // msgs[i] = "Comment " + verb + ": " + path; } else { throw new SocialModerationException( "Not a comment: " + path, ModerationConstants.ERR_NOT_A_COMMENT); } } } } catch (final JSONException je) { log.error(je.getLocalizedMessage(), je.getCause()); throw new SocialModerationException( je.getLocalizedMessage(), ModerationConstants.ERR_FLAGGED_ACTION, je.getCause()); } catch (final Exception e) { log.error(e.getLocalizedMessage(), e.getCause()); throw new SocialModerationException( e.getLocalizedMessage(), ModerationConstants.ERR_FLAGGED_ACTION, e.getCause()); } }
public void internalImportContent( ContentManager contentManager, JSONObject json, String path, boolean replaceProperties, AccessControlManager accessControlManager) throws JSONException, StorageClientException, AccessDeniedException { Iterator<String> keys = json.keys(); Map<String, Object> properties = new HashMap<String, Object>(); List<AclModification> modifications = Lists.newArrayList(); while (keys.hasNext()) { String key = keys.next(); if (!key.startsWith("jcr:")) { Object obj = json.get(key); String pathKey = getPathElement(key); Class<?> typeHint = getElementType(key); if (obj instanceof JSONObject) { if (key.endsWith("@grant")) { JSONObject acl = (JSONObject) obj; int bitmap = getPermissionBitMap(acl.getJSONArray("permission")); Operation op = getOperation(acl.getString("operation")); modifications.add(new AclModification(AclModification.grantKey(pathKey), bitmap, op)); } else if (key.endsWith("@deny")) { JSONObject acl = (JSONObject) obj; int bitmap = getPermissionBitMap(acl.getJSONArray("permission")); Operation op = getOperation(acl.getString("operation")); modifications.add(new AclModification(AclModification.denyKey(pathKey), bitmap, op)); } else if (key.endsWith("@Delete")) { StorageClientUtils.deleteTree(contentManager, path); } else { // need to do somethingwith delete here internalImportContent( contentManager, (JSONObject) obj, path + "/" + pathKey, replaceProperties, accessControlManager); } } else if (obj instanceof JSONArray) { if (key.endsWith("@Delete")) { properties.put(pathKey, new RemoveProperty()); } else { // This represents a multivalued property JSONArray arr = (JSONArray) obj; properties.put(pathKey, getArray(arr, typeHint)); } } else { if (key.endsWith("@Delete")) { properties.put(pathKey, new RemoveProperty()); } else { properties.put(pathKey, getObject(obj, typeHint)); } } } } Content content = contentManager.get(path); if (content == null) { contentManager.update(new Content(path, properties)); LOGGER.info("Created Node {} {}", path, properties); } else { for (Entry<String, Object> e : properties.entrySet()) { if (replaceProperties || !content.hasProperty(e.getKey())) { LOGGER.info("Updated Node {} {} {} ", new Object[] {path, e.getKey(), e.getValue()}); content.setProperty(e.getKey(), e.getValue()); } } contentManager.update(content); } if (modifications.size() > 0) { accessControlManager.setAcl( Security.ZONE_CONTENT, path, modifications.toArray(new AclModification[modifications.size()])); } }