src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
RedirectClientCallback extends AbstractHttpClientCallback { public void setLocation(String location) { this.location = location; } @Override void handle(HttpServletRequest request, HttpServletResponse response); void setLocation(String location); } | @Test public void testExternalUrlsArePassedAsIs() throws Exception { callback.setLocation("http: expect(request.getRequestURI()).andReturn("/really/does/not/matter"); expect(request.getRequestURL()).andReturn(new StringBuffer("http: response.sendRedirect("http: }
@Test public void testRelativeURLsAreSupported() throws Exception { callback.setLocation("bar"); expect(request.getRequestURI()).andReturn("/really/does/not/matter"); expect(request.getRequestURL()).andReturn(new StringBuffer("http: response.sendRedirect("bar"); }
@Test public void testAbsoluteURLsArePrefixedWithContextPath() throws Exception { callback.setLocation("/bar"); expect(request.getContextPath()).andReturn("/foo"); expect(request.getRequestURI()).andReturn("/foo/does/not/matter"); expect(request.getRequestURL()).andReturn(new StringBuffer("http: response.sendRedirect("/foo/bar"); }
@Test public void testDoesNothingIfCurrentRequestURLIsTarget() throws Exception { callback.setLocation("/some/path"); expect(request.getContextPath()).andReturn("/foo"); expect(request.getRequestURI()).andReturn("/foo/some/path"); }
@Test public void testTargetUrlIsFormattedWithEncodedRequestURL() throws Exception { callback.setLocation("http: expect(request.getRequestURI()).andReturn("/foo/some/path"); expect(request.getRequestURL()).andReturn(new StringBuffer("http: response.sendRedirect("http: }
@Test public void testRedirectWithParameters() throws Exception { final TestWebContext ctx = new TestWebContext(); ctx.addParameter("parameter1", "value1"); ctx.addParameter("parameter2", "value2"); MgnlContext.setInstance(ctx); callback.setLocation("http: expect(request.getRequestURI()).andReturn("/foo/some/path"); expect(request.getRequestURL()).andReturn(new StringBuffer("http: response.sendRedirect("http: } |
AccessManagerImpl implements AccessManager, Serializable { @Override public long getPermissions(String path) { if (userPermissions == null) { return Permission.NONE; } long permission = 0; int patternLength = 0; for (Permission p : userPermissions) { if (p.match(path)) { int l = p.getPattern().getLength(); if (patternLength == l && (permission < p.getPermissions())) { permission = p.getPermissions(); } else if (patternLength < l) { patternLength = l; permission = p.getPermissions(); } } } return permission; } @Override boolean isGranted(String path, long permissions); @Override void setPermissionList(List<Permission> permissions); @Override List<Permission> getPermissionList(); @Override long getPermissions(String path); } | @Test public void testGetPermissions() { final Permission accessChildrenPermission = new PermissionImpl(); accessChildrenPermission.setPattern(new SimpleUrlPattern("/admin/test/*")); accessChildrenPermission.setPermissions(8); final List permissionList = new ArrayList(); permissionList.add(accessChildrenPermission); AccessManagerImpl ami = new AccessManagerImpl(); assertEquals(0, ami.getPermissions(TEST)); assertEquals(0, ami.getPermissions(TEST_LANG)); ami.setPermissionList(permissionList); assertEquals(0, ami.getPermissions(TEST)); assertEquals(8, ami.getPermissions(TEST_LANG)); permissionList.clear(); final Permission accessParentPermission = new PermissionImpl(); accessParentPermission.setPattern(new SimpleUrlPattern("/admin/test")); accessParentPermission.setPermissions(8); permissionList.add(accessParentPermission); assertEquals(8, ami.getPermissions(TEST)); assertEquals(0, ami.getPermissions(TEST_LANG)); permissionList.clear(); final Permission accessAllPermission = new PermissionImpl(); accessAllPermission.setPattern(new SimpleUrlPattern("/admin/test*")); accessAllPermission.setPermissions(8); permissionList.add(accessAllPermission); assertEquals(8, ami.getPermissions(TEST)); assertEquals(8, ami.getPermissions(TEST_LANG)); } |
TemplatingFunctions { public List<ContentMap> ancestors(ContentMap contentMap) throws RepositoryException { return ancestors(contentMap, null); } @Inject TemplatingFunctions(Provider<AggregationState> aggregationStateProvider); Node asJCRNode(ContentMap contentMap); ContentMap asContentMap(Node content); List<Node> children(Node content); List<Node> children(Node content, String nodeTypeName); List<ContentMap> children(ContentMap content); List<ContentMap> children(ContentMap content, String nodeTypeName); ContentMap root(ContentMap contentMap); ContentMap root(ContentMap contentMap, String nodeTypeName); Node root(Node content); Node root(Node content, String nodeTypeName); ContentMap parent(ContentMap contentMap); ContentMap parent(ContentMap contentMap, String nodeTypeName); Node parent(Node content); Node parent(Node content, String nodeTypeName); ContentMap page(ContentMap content); Node page(Node content); List<ContentMap> ancestors(ContentMap contentMap); List<ContentMap> ancestors(ContentMap contentMap, String nodeTypeName); List<Node> ancestors(Node content); List<Node> ancestors(Node content, String nodeTypeName); Node inherit(Node content); Node inherit(Node content, String relPath); ContentMap inherit(ContentMap content); ContentMap inherit(ContentMap content, String relPath); Property inheritProperty(Node content, String relPath); Property inheritProperty(ContentMap content, String relPath); List<Node> inheritList(Node content, String relPath); List<ContentMap> inheritList(ContentMap content, String relPath); boolean isInherited(Node content); boolean isInherited(ContentMap content); boolean isFromCurrentPage(Node content); boolean isFromCurrentPage(ContentMap content); String link(String workspace, String nodeIdentifier); @Deprecated String link(Property property); String link(Node content); String link(ContentMap contentMap); String language(); String externalLink(Node content, String linkPropertyName); String externalLink(ContentMap content, String linkPropertyName); String externalLinkTitle(Node content, String linkPropertyName, String linkTitlePropertyName); String externalLinkTitle(ContentMap content, String linkPropertyName, String linkTitlePropertyName); boolean isEditMode(); boolean isPreviewMode(); boolean isAuthorInstance(); boolean isPublicInstance(); String createHtmlAttribute(String name, String value); SiblingsHelper siblings(Node node); SiblingsHelper siblings(ContentMap node); Node content(String path); Node content(String repository, String path); Node contentByIdentifier(String id); Node contentByIdentifier(String repository, String id); List<ContentMap> asContentMapList(Collection<Node> nodeList); List<Node> asNodeList(Collection<ContentMap> contentMapList); ContentMap decode(ContentMap content); Node decode(Node content); Node encode(Node content); String metaData(Node content, String property); String metaData(ContentMap content, String property); Collection<Node> search(String workspace, String statement, String language, String returnItemType); Collection<Node> simpleSearch(String workspace, String statement, String returnItemType, String startPath); } | @Test public void testAncestorsFromNodeDepth1() throws RepositoryException { List<Node> resultList = functions.ancestors(topPage); assertEquals(resultList.size(), 0); }
@Test public void testAncestorPagesFromNodeDepth1() throws RepositoryException { List<Node> resultList = functions.ancestors(topPage, NodeTypes.Page.NAME); assertEquals(resultList.size(), 0); }
@Test public void testAncestorsFromComponentNodeDepth2() throws RepositoryException { List<Node> resultList = functions.ancestors(topPageComponent); assertEquals(resultList.size(), 1); assertNodeEqualsNode(topPage, resultList.get(0)); }
@Test public void testAncestorPagesFromComponentNodeDepth4() throws RepositoryException { List<Node> compareList = new ArrayList<Node>(); compareList.add(topPage); compareList.add(childPage); Iterator<Node> itCompare = compareList.iterator(); List<Node> resultList = functions.ancestors(childPageComponent, NodeTypes.Page.NAME); assertEquals(compareList.size(), resultList.size()); for (Iterator<Node> itResult = resultList.iterator(); itResult.hasNext();) { assertNodeEqualsNode(itResult.next(), itCompare.next()); } }
@Test public void testAncestorsFromSubComponentNodeDepth5() throws RepositoryException { Node subSubComponent = childPageComponent.addNode("subSubComponent", NodeTypes.Component.NAME); List<Node> compareList = new ArrayList<Node>(); compareList.add(topPage); compareList.add(childPage); compareList.add(childPageComponent); Iterator<Node> itCompare = compareList.iterator(); List<Node> resultList = functions.ancestors(subSubComponent); assertEquals(compareList.size(), resultList.size()); for (Iterator<Node> itResult = resultList.iterator(); itResult.hasNext();) { assertNodeEqualsNode(itResult.next(), itCompare.next()); } }
@Test public void testAncestorPagesFromSubComponentNodeDepth5() throws RepositoryException { Node subSubComponent = childPageComponent.addNode("subSubComponent", NodeTypes.Component.NAME); List<Node> compareList = new ArrayList<Node>(); compareList.add(topPage); compareList.add(childPage); Iterator<Node> itCompare = compareList.iterator(); List<Node> resultList = functions.ancestors(subSubComponent, NodeTypes.Page.NAME); assertEquals(compareList.size(), resultList.size()); for (Iterator<Node> itResult = resultList.iterator(); itResult.hasNext();) { assertNodeEqualsNode(itResult.next(), itCompare.next()); } }
@Test public void testAncestorsFromContentMapDepth1() throws RepositoryException { List<ContentMap> resultList = functions.ancestors(topPageContentMap); assertEquals(resultList.size(), 0); }
@Test public void testAncestorPagesFromContentMapDepth1() throws RepositoryException { List<ContentMap> resultList = functions.ancestors(topPageContentMap, NodeTypes.Page.NAME); assertEquals(resultList.size(), 0); }
@Test public void testAncestorsFromComponentContentMapDepth2() throws RepositoryException { List<ContentMap> resultList = functions.ancestors(topPageComponentContentMap); assertEquals(resultList.size(), 1); assertMapEqualsNode(topPage, resultList.get(0)); }
@Test public void testAncestorPagesFromComponentContentMapDepth4() throws RepositoryException { List<Node> compareList = new ArrayList<Node>(); compareList.add(topPage); compareList.add(childPage); Iterator<Node> itCompare = compareList.iterator(); List<ContentMap> resultList = functions.ancestors(childPageComponentContentMap, NodeTypes.Page.NAME); assertEquals(compareList.size(), resultList.size()); for (Iterator<ContentMap> itResult = resultList.iterator(); itResult.hasNext();) { assertMapEqualsNode(itCompare.next(), itResult.next()); } }
@Test public void testAncestorsFromSubComponentConentMapDepth5() throws RepositoryException { ContentMap subComponentContentMap = new ContentMap(childPageComponent.addNode("subSubComponent", NodeTypes.Component.NAME)); List<Node> compareList = new ArrayList<Node>(); compareList.add(topPage); compareList.add(childPage); compareList.add(childPageComponent); Iterator<Node> itCompare = compareList.iterator(); List<ContentMap> resultList = functions.ancestors(subComponentContentMap); assertEquals(compareList.size(), resultList.size()); for (Iterator<ContentMap> itResult = resultList.iterator(); itResult.hasNext();) { assertMapEqualsNode(itCompare.next(), itResult.next()); } }
@Test public void testAncestorPagesFromSubComponentConentMapDepth5() throws RepositoryException { ContentMap subComponentContentMap = new ContentMap(childPageComponent.addNode("subSubComponent", NodeTypes.Component.NAME)); List<Node> compareList = new ArrayList<Node>(); compareList.add(topPage); compareList.add(childPage); Iterator<Node> itCompare = compareList.iterator(); List<ContentMap> resultList = functions.ancestors(subComponentContentMap, NodeTypes.Page.NAME); assertEquals(compareList.size(), resultList.size()); for (Iterator<ContentMap> itResult = resultList.iterator(); itResult.hasNext();) { assertMapEqualsNode(itCompare.next(), itResult.next()); } } |
Security { private static void mergePrincipals(PrincipalCollectionImpl principalCollection, List<Principal> acls) { for (Principal principal : acls) { ACL princ = (ACL) principal; if (principalCollection.contains(princ.getName())) { ACL oldACL = (ACL) principalCollection.get(princ.getName()); Collection<Permission> permissions = new HashSet<Permission>(oldACL.getList()); permissions.addAll(princ.getList()); principalCollection.remove(oldACL); princ = new ACLImpl(princ.getName(), new ArrayList<Permission>(permissions)); } principalCollection.add(princ); } } static RoleManager getRoleManager(); static UserManager getUserManager(); static GroupManager getGroupManager(); static SecuritySupport getSecuritySupport(); static User getAnonymousUser(); static User getSystemUser(); static Subject getSystemSubject(); static Subject getAnonymousSubject(); } | @Test public void testMergePrincipals() throws AccessDeniedException { Subject subject = Security.getAnonymousSubject(); assertEquals("anonymous", subject.getPrincipals(User.class).iterator().next().getName()); Iterator<PrincipalCollectionImpl> principalCollectionIter = subject.getPrincipals(PrincipalCollectionImpl.class).iterator(); Iterator<Principal> principalIter = principalCollectionIter.next().iterator(); assertEquals("website",principalIter.next().getName()); assertEquals("data",principalIter.next().getName()); assertEquals("imaging",principalIter.next().getName()); assertFalse(principalIter.hasNext()); } |
ContentRepository { public static Provider getRepositoryProvider(String repositoryOrLogicalWorkspace) { RepositoryManager repositoryManager = Components.getComponent(RepositoryManager.class); if (!repositoryManager.hasRepository(repositoryOrLogicalWorkspace)) { repositoryOrLogicalWorkspace = getMappedRepositoryName(repositoryOrLogicalWorkspace); } return repositoryManager.getRepositoryProvider(repositoryOrLogicalWorkspace); } private ContentRepository(); static void init(); static void shutdown(); static boolean checkIfInitialized(); static boolean checkIfInitialized(String logicalWorkspaceName); static void reload(); static void loadRepository(RepositoryDefinition repositoryDefinition); static void loadWorkspace(String repositoryId, String workspaceName); static String getParentRepositoryName(String physicalWorkspaceName); static String getMappedRepositoryName(String logicalWorkspaceName); static String getMappedWorkspaceName(String logicalWorkspaceName); static void addMappedRepositoryName(String logicalWorkspaceName, String repositoryName); static void addMappedRepositoryName(String logicalWorkspaceName, String repositoryName, String workspaceName); static String getDefaultWorkspace(String repositoryId); static Repository getRepository(String repositoryOrLogicalWorkspace); static Provider getRepositoryProvider(String repositoryOrLogicalWorkspace); static RepositoryDefinition getRepositoryMapping(String repositoryOrLogicalWorkspace); static boolean hasRepositoryMapping(String repositoryOrLogicalWorkspace); static Iterator<String> getAllRepositoryNames(); static String getInternalWorkspaceName(String physicalWorkspaceName); static final String WEBSITE; static final String USERS; static final String USER_ROLES; static final String USER_GROUPS; static final String CONFIG; static final String VERSION_STORE; static final String NAMESPACE_PREFIX; static final String NAMESPACE_URI; static final String DEFAULT_WORKSPACE; static String REPOSITORY_USER; static String REPOSITORY_PSWD; } | @Test @Ignore public void testUnknownRepositoryShouldAlsoYieldMeaningfulExceptionMessageForRepositoryProviders() { try { ContentRepository.getRepositoryProvider("dummy"); fail("should have failed, since we haven't set any repository at all"); } catch (Throwable t) { assertEquals("Failed to retrieve repository provider 'dummy' (mapped as 'dummy'). Your Magnolia instance might not have been initialized properly.", t.getMessage()); } } |
URI2RepositoryMapping { public String getURI(String handle) { try { return getURI(LinkUtil.createLinkInstance(this.getRepository(), handle, null, null, null)); } catch (LinkException e) { return handle; } } URI2RepositoryMapping(String uriPrefix, String repository, String handlePrefix); URI2RepositoryMapping(); boolean matches(String uri); String getHandle(String uri); String getURI(String handle); String getURI(Link uuidLink); String getHandlePrefix(); void setHandlePrefix(String handlePrefix); String getRepository(); void setRepository(String repository); String getURIPrefix(); void setURIPrefix(String uriPrefix); @Override String toString(); } | @Test public void testGetUri() throws Exception { ComponentsTestUtil.setInstance(ServerConfiguration.class, new ServerConfiguration()); Components.getComponent(ServerConfiguration.class).setDefaultExtension("bla"); URI2RepositoryMapping mapping = new URI2RepositoryMapping(); mapping.setRepository("dummy-repo"); mapping.setURIPrefix("/blabla/"); final Workspace ws = mock(Workspace.class); final Context context = mock(Context.class); final Session session = mock(Session.class); final Node node = mock(Node.class); final Property property = mock(Property.class); final Property property2 = mock(Property.class); when(context.getJCRSession("dummy-repo")).thenReturn(session); when(session.nodeExists("/Test/image")).thenReturn(true); when(session.getNode("/Test/image")).thenReturn(node); when(node.isNodeType(NodeTypes.Resource.NAME)).thenReturn(true); when(node.hasProperty("fileName")).thenReturn(true); when(node.getProperty("fileName")).thenReturn(property); when(property.getString()).thenReturn("blah"); when(node.getSession()).thenReturn(session); when(session.getWorkspace()).thenReturn(ws); when(ws.getName()).thenReturn("dummy-repo"); when(node.hasProperty("extension")).thenReturn(true); when(node.getProperty("extension")).thenReturn(property2); when(property2.getString()).thenReturn("jpg"); MgnlContext.setInstance(context); String uri = mapping.getURI("/Test/image"); assertEquals("Detected double slash in generated link path.",-1, uri.indexOf(" assertTrue("Incorrect file name generated.",uri.endsWith("/blah.jpg")); } |
URI2RepositoryMapping { public String getHandle(String uri) { String handle; handle = StringUtils.removeStart(uri, this.URIPrefix); if (StringUtils.isNotEmpty(this.handlePrefix)) { StringUtils.removeStart(handle, "/"); handle = this.handlePrefix + "/" + handle; } String fileName = StringUtils.substringAfterLast(handle, "/"); String extension = StringUtils.substringAfterLast(fileName, "."); handle = StringUtils.removeEnd(handle, "." + extension); handle = cleanHandle(handle); try{ final Session session = MgnlContext.getJCRSession(this.repository); if (!session.itemExists(handle)) { String maybeHandle = (this.handlePrefix.endsWith("/") ? "/" : "") + StringUtils.removeStart(handle, this.handlePrefix); if (session.itemExists(maybeHandle) || (maybeHandle.lastIndexOf("/") > 0 && session.itemExists(StringUtils.substringBeforeLast(maybeHandle, "/")))) { return maybeHandle; } } }catch(RepositoryException e){ log.debug(e.getMessage(), e); } return handle; } URI2RepositoryMapping(String uriPrefix, String repository, String handlePrefix); URI2RepositoryMapping(); boolean matches(String uri); String getHandle(String uri); String getURI(String handle); String getURI(Link uuidLink); String getHandlePrefix(); void setHandlePrefix(String handlePrefix); String getRepository(); void setRepository(String repository); String getURIPrefix(); void setURIPrefix(String uriPrefix); @Override String toString(); } | @Test public void testGetHandleStripsExtensionInclTheDot() throws Exception { WebContext context = mock(WebContext.class); Session session = mock(Session.class); MgnlContext.setInstance(context); MockRepositoryAcquiringStrategy strategy = Components.getComponent(MockRepositoryAcquiringStrategy.class); strategy.addSession("config", session); final ServerConfiguration serverConfiguration = new ServerConfiguration(); ComponentsTestUtil.setInstance(ServerConfiguration.class, serverConfiguration); Components.getComponent(ServerConfiguration.class).setDefaultExtension("ext"); ComponentsTestUtil.setInstance(URI2RepositoryManager.class, new URI2RepositoryManager()); when(context.getJCRSession("website")).thenReturn(session); String handle = Components.getComponent(URI2RepositoryManager.class).getHandle("/blah.ext"); assertEquals("/blah", handle); handle = Components.getComponent(URI2RepositoryManager.class).getHandle("/b.l/ah.ext"); assertEquals("/b.l/ah", handle); handle = Components.getComponent(URI2RepositoryManager.class).getHandle("/bl.ah.ext"); assertEquals("/bl.ah", handle); }
@Test public void testGetHandleWhenLinkWithPrefixHandleExistInRepo() throws Exception{ WebContext context = mock(WebContext.class); Session session = mock(Session.class); MgnlContext.setInstance(context); URI2RepositoryManager uri2RepositoryManager = new URI2RepositoryManager(); uri2RepositoryManager.addMapping(new URI2RepositoryMapping("/demo-project", "website", "/demoproject/year2010")); ComponentsTestUtil.setInstance(URI2RepositoryManager.class, uri2RepositoryManager); when(context.getJCRSession("website")).thenReturn(session); when(session.nodeExists("/demoproject/year2010/blah")).thenReturn(true); String handle = Components.getComponent(URI2RepositoryManager.class).getHandle("/demo-project/blah.ext"); assertEquals("/demoproject/year2010/blah", handle); }
@Test public void testGetHandleWhenLinkWithPrefixHandleDoesNotExistInRepo() throws Exception{ WebContext context = mock(WebContext.class); Session session = mock(Session.class); MgnlContext.setInstance(context); URI2RepositoryManager uri2RepositoryManager = new URI2RepositoryManager(); uri2RepositoryManager.addMapping(new URI2RepositoryMapping("", "website", "/blabla")); ComponentsTestUtil.setInstance(URI2RepositoryManager.class, uri2RepositoryManager); when(context.getJCRSession("website")).thenReturn(session); when(session.itemExists("/demoproject/year2010/blah")).thenReturn(true); when(session.itemExists("/blah")).thenReturn(true); String handle = Components.getComponent(URI2RepositoryManager.class).getHandle("/blah.ext"); assertEquals("/blah", handle); } |
AggregationState { protected String stripContextPathIfExists(String uri) { String contextPath = MgnlContext.getContextPath(); if (uri != null && uri.startsWith(contextPath + "/")) { return StringUtils.removeStart(uri, contextPath); } return uri; } void setOriginalURI(String originalURI); void setOriginalBrowserURI(String originalBrowserURI); void setCurrentURI(String currentURI); void setQueryString(String queryString); String getQueryString(); String getCurrentURI(); String getCharacterEncoding(); String getOriginalURI(); String getOriginalURL(); void setOriginalURL(String originalURL); String getOriginalBrowserURI(); String getOriginalBrowserURL(); void setOriginalBrowserURL(String originalBrowserURL); void setCharacterEncoding(String characterEncoding); String getExtension(); void setExtension(String extension); File getFile(); void setFile(File file); String getHandle(); void setHandle(String handle); Content getMainContent(); void setMainContent(Content mainContent); Content getCurrentContent(); void setCurrentContent(Content currentContent); String getRepository(); void setRepository(String repository); String getSelector(); void setSelector(String selector); String getTemplateName(); void setTemplateName(String templateName); Locale getLocale(); void setLocale(Locale locale); boolean isPreviewMode(); void setPreviewMode(boolean previewMode); Channel getChannel(); void setChannel(Channel channel); void resetURIs(); String[] getSelectors(); } | @Test public void testUriDecodingShouldStripCtxPath() { assertEquals("/pouet", aggState.stripContextPathIfExists("/foo/pouet")); }
@Test public void testUriDecodingShouldReturnPassedURIDoesntContainCtxPath() { assertEquals("/pouet", aggState.stripContextPathIfExists("/pouet")); } |
AggregationState { public String[] getSelectors() { return selectors; } void setOriginalURI(String originalURI); void setOriginalBrowserURI(String originalBrowserURI); void setCurrentURI(String currentURI); void setQueryString(String queryString); String getQueryString(); String getCurrentURI(); String getCharacterEncoding(); String getOriginalURI(); String getOriginalURL(); void setOriginalURL(String originalURL); String getOriginalBrowserURI(); String getOriginalBrowserURL(); void setOriginalBrowserURL(String originalBrowserURL); void setCharacterEncoding(String characterEncoding); String getExtension(); void setExtension(String extension); File getFile(); void setFile(File file); String getHandle(); void setHandle(String handle); Content getMainContent(); void setMainContent(Content mainContent); Content getCurrentContent(); void setCurrentContent(Content currentContent); String getRepository(); void setRepository(String repository); String getSelector(); void setSelector(String selector); String getTemplateName(); void setTemplateName(String templateName); Locale getLocale(); void setLocale(Locale locale); boolean isPreviewMode(); void setPreviewMode(boolean previewMode); Channel getChannel(); void setChannel(Channel channel); void resetURIs(); String[] getSelectors(); } | @Test public void testGetSelectors() throws Exception { aggState.setSelector(""); assertEquals("", aggState.getSelector()); String[]selectors = aggState.getSelectors(); assertTrue(selectors.length == 0); aggState.setSelector("~~"); assertEquals("~~", aggState.getSelector()); selectors = aggState.getSelectors(); assertTrue(selectors.length == 0); aggState.setSelector("foo.baz"); assertEquals("foo.baz", aggState.getSelector()); selectors = aggState.getSelectors(); assertTrue(selectors.length == 1); assertEquals("foo.baz", selectors[0]); aggState.setSelector("foo~bar.baz"); assertEquals("foo~bar.baz", aggState.getSelector()); selectors = aggState.getSelectors(); assertTrue(selectors.length == 2); assertEquals("foo", selectors[0]); assertEquals("bar.baz", selectors[1]); aggState.setSelector("foo~bar.baz=qux~meh"); assertEquals("foo~bar.baz=qux~meh", aggState.getSelector()); selectors = aggState.getSelectors(); assertTrue(selectors.length == 3); assertEquals("foo", selectors[0]); assertEquals("bar.baz=qux", selectors[1]); assertEquals("meh", selectors[2]); assertEquals("qux", MgnlContext.getAttribute("bar.baz")); } |
MetaData { public String getTitle() { return getStringProperty(TITLE); } protected MetaData(Node workingNode, AccessManager ignoredAccessManager); MetaData(Node workingNode); String getTitle(); void setTitle(String value); void setCreationDate(); Calendar getCreationDate(); void setActivated(); void setUnActivated(); boolean getIsActivated(); int getActivationStatus(); void setLastActivationActionDate(); Calendar getLastActionDate(); void setModificationDate(); Calendar getModificationDate(); String getAuthorId(); void setAuthorId(String value); String getActivatorId(); void setActivatorId(String value); String getTemplate(); void setTemplate(String value); void setProperty(String name, String value); void setProperty(String name, long value); void setProperty(String name, double value); void setProperty(String name, boolean value); void setProperty(String name, Calendar value); boolean getBooleanProperty(String name); double getDoubleProperty(String name); long getLongProperty(String name); String getStringProperty(String name); Calendar getDateProperty(String name); void removeProperty(String name); static final String TITLE; static final String CREATION_DATE; static final String LAST_MODIFIED; static final String LAST_ACTION; static final String AUTHOR_ID; static final String ACTIVATOR_ID; static final String TEMPLATE; static final String TEMPLATE_TYPE; static final String ACTIVATED; static final String DEFAULT_META_NODE; static final int ACTIVATION_STATUS_NOT_ACTIVATED; static final int ACTIVATION_STATUS_MODIFIED; static final int ACTIVATION_STATUS_ACTIVATED; } | @Test(expected = IllegalArgumentException.class) public void testGetTitleThrowsException() { new MetaData(root).getTitle(); } |
MetaData { public void setTitle(String value) { setProperty(TITLE, value); } protected MetaData(Node workingNode, AccessManager ignoredAccessManager); MetaData(Node workingNode); String getTitle(); void setTitle(String value); void setCreationDate(); Calendar getCreationDate(); void setActivated(); void setUnActivated(); boolean getIsActivated(); int getActivationStatus(); void setLastActivationActionDate(); Calendar getLastActionDate(); void setModificationDate(); Calendar getModificationDate(); String getAuthorId(); void setAuthorId(String value); String getActivatorId(); void setActivatorId(String value); String getTemplate(); void setTemplate(String value); void setProperty(String name, String value); void setProperty(String name, long value); void setProperty(String name, double value); void setProperty(String name, boolean value); void setProperty(String name, Calendar value); boolean getBooleanProperty(String name); double getDoubleProperty(String name); long getLongProperty(String name); String getStringProperty(String name); Calendar getDateProperty(String name); void removeProperty(String name); static final String TITLE; static final String CREATION_DATE; static final String LAST_MODIFIED; static final String LAST_ACTION; static final String AUTHOR_ID; static final String ACTIVATOR_ID; static final String TEMPLATE; static final String TEMPLATE_TYPE; static final String ACTIVATED; static final String DEFAULT_META_NODE; static final int ACTIVATION_STATUS_NOT_ACTIVATED; static final int ACTIVATION_STATUS_MODIFIED; static final int ACTIVATION_STATUS_ACTIVATED; } | @Test(expected = IllegalArgumentException.class) public void testSetTitleThrowsException() { new MetaData(root).setTitle("Title"); } |
MetaData { public void setCreationDate() { Calendar value = new GregorianCalendar(TimeZone.getDefault()); setProperty(CREATION_DATE, value); } protected MetaData(Node workingNode, AccessManager ignoredAccessManager); MetaData(Node workingNode); String getTitle(); void setTitle(String value); void setCreationDate(); Calendar getCreationDate(); void setActivated(); void setUnActivated(); boolean getIsActivated(); int getActivationStatus(); void setLastActivationActionDate(); Calendar getLastActionDate(); void setModificationDate(); Calendar getModificationDate(); String getAuthorId(); void setAuthorId(String value); String getActivatorId(); void setActivatorId(String value); String getTemplate(); void setTemplate(String value); void setProperty(String name, String value); void setProperty(String name, long value); void setProperty(String name, double value); void setProperty(String name, boolean value); void setProperty(String name, Calendar value); boolean getBooleanProperty(String name); double getDoubleProperty(String name); long getLongProperty(String name); String getStringProperty(String name); Calendar getDateProperty(String name); void removeProperty(String name); static final String TITLE; static final String CREATION_DATE; static final String LAST_MODIFIED; static final String LAST_ACTION; static final String AUTHOR_ID; static final String ACTIVATOR_ID; static final String TEMPLATE; static final String TEMPLATE_TYPE; static final String ACTIVATED; static final String DEFAULT_META_NODE; static final int ACTIVATION_STATUS_NOT_ACTIVATED; static final int ACTIVATION_STATUS_MODIFIED; static final int ACTIVATION_STATUS_ACTIVATED; } | @Test public void testSetCreationDate() throws RepositoryException { new MetaData(root).setCreationDate(); assertTrue(root.hasProperty(NodeTypes.Created.CREATED)); } |
MetaData { public Calendar getCreationDate() { return this.getDateProperty(CREATION_DATE); } protected MetaData(Node workingNode, AccessManager ignoredAccessManager); MetaData(Node workingNode); String getTitle(); void setTitle(String value); void setCreationDate(); Calendar getCreationDate(); void setActivated(); void setUnActivated(); boolean getIsActivated(); int getActivationStatus(); void setLastActivationActionDate(); Calendar getLastActionDate(); void setModificationDate(); Calendar getModificationDate(); String getAuthorId(); void setAuthorId(String value); String getActivatorId(); void setActivatorId(String value); String getTemplate(); void setTemplate(String value); void setProperty(String name, String value); void setProperty(String name, long value); void setProperty(String name, double value); void setProperty(String name, boolean value); void setProperty(String name, Calendar value); boolean getBooleanProperty(String name); double getDoubleProperty(String name); long getLongProperty(String name); String getStringProperty(String name); Calendar getDateProperty(String name); void removeProperty(String name); static final String TITLE; static final String CREATION_DATE; static final String LAST_MODIFIED; static final String LAST_ACTION; static final String AUTHOR_ID; static final String ACTIVATOR_ID; static final String TEMPLATE; static final String TEMPLATE_TYPE; static final String ACTIVATED; static final String DEFAULT_META_NODE; static final int ACTIVATION_STATUS_NOT_ACTIVATED; static final int ACTIVATION_STATUS_MODIFIED; static final int ACTIVATION_STATUS_ACTIVATED; } | @Test public void testGetCreationDate() throws RepositoryException { Calendar expected = Calendar.getInstance(); root.setProperty(NodeTypes.Created.CREATED, expected); Calendar actual = new MetaData(root).getCreationDate(); assertEquals(expected.getTimeInMillis(), actual.getTimeInMillis()); } |
MetaData { public void setActivated() { setProperty(ACTIVATED, true); } protected MetaData(Node workingNode, AccessManager ignoredAccessManager); MetaData(Node workingNode); String getTitle(); void setTitle(String value); void setCreationDate(); Calendar getCreationDate(); void setActivated(); void setUnActivated(); boolean getIsActivated(); int getActivationStatus(); void setLastActivationActionDate(); Calendar getLastActionDate(); void setModificationDate(); Calendar getModificationDate(); String getAuthorId(); void setAuthorId(String value); String getActivatorId(); void setActivatorId(String value); String getTemplate(); void setTemplate(String value); void setProperty(String name, String value); void setProperty(String name, long value); void setProperty(String name, double value); void setProperty(String name, boolean value); void setProperty(String name, Calendar value); boolean getBooleanProperty(String name); double getDoubleProperty(String name); long getLongProperty(String name); String getStringProperty(String name); Calendar getDateProperty(String name); void removeProperty(String name); static final String TITLE; static final String CREATION_DATE; static final String LAST_MODIFIED; static final String LAST_ACTION; static final String AUTHOR_ID; static final String ACTIVATOR_ID; static final String TEMPLATE; static final String TEMPLATE_TYPE; static final String ACTIVATED; static final String DEFAULT_META_NODE; static final int ACTIVATION_STATUS_NOT_ACTIVATED; static final int ACTIVATION_STATUS_MODIFIED; static final int ACTIVATION_STATUS_ACTIVATED; } | @Test public void testSetActivated() throws RepositoryException { new MetaData(root).setActivated(); assertTrue(root.getProperty(NodeTypes.Activatable.ACTIVATION_STATUS).getBoolean()); } |
MetaData { public void setUnActivated() { setProperty(ACTIVATED, false); } protected MetaData(Node workingNode, AccessManager ignoredAccessManager); MetaData(Node workingNode); String getTitle(); void setTitle(String value); void setCreationDate(); Calendar getCreationDate(); void setActivated(); void setUnActivated(); boolean getIsActivated(); int getActivationStatus(); void setLastActivationActionDate(); Calendar getLastActionDate(); void setModificationDate(); Calendar getModificationDate(); String getAuthorId(); void setAuthorId(String value); String getActivatorId(); void setActivatorId(String value); String getTemplate(); void setTemplate(String value); void setProperty(String name, String value); void setProperty(String name, long value); void setProperty(String name, double value); void setProperty(String name, boolean value); void setProperty(String name, Calendar value); boolean getBooleanProperty(String name); double getDoubleProperty(String name); long getLongProperty(String name); String getStringProperty(String name); Calendar getDateProperty(String name); void removeProperty(String name); static final String TITLE; static final String CREATION_DATE; static final String LAST_MODIFIED; static final String LAST_ACTION; static final String AUTHOR_ID; static final String ACTIVATOR_ID; static final String TEMPLATE; static final String TEMPLATE_TYPE; static final String ACTIVATED; static final String DEFAULT_META_NODE; static final int ACTIVATION_STATUS_NOT_ACTIVATED; static final int ACTIVATION_STATUS_MODIFIED; static final int ACTIVATION_STATUS_ACTIVATED; } | @Test public void testSetUnActivated() throws RepositoryException { root.setProperty(NodeTypes.Activatable.ACTIVATION_STATUS, true); new MetaData(root).setUnActivated(); assertFalse(root.getProperty(NodeTypes.Activatable.ACTIVATION_STATUS).getBoolean()); } |
MetaData { public boolean getIsActivated() { return getBooleanProperty(ACTIVATED); } protected MetaData(Node workingNode, AccessManager ignoredAccessManager); MetaData(Node workingNode); String getTitle(); void setTitle(String value); void setCreationDate(); Calendar getCreationDate(); void setActivated(); void setUnActivated(); boolean getIsActivated(); int getActivationStatus(); void setLastActivationActionDate(); Calendar getLastActionDate(); void setModificationDate(); Calendar getModificationDate(); String getAuthorId(); void setAuthorId(String value); String getActivatorId(); void setActivatorId(String value); String getTemplate(); void setTemplate(String value); void setProperty(String name, String value); void setProperty(String name, long value); void setProperty(String name, double value); void setProperty(String name, boolean value); void setProperty(String name, Calendar value); boolean getBooleanProperty(String name); double getDoubleProperty(String name); long getLongProperty(String name); String getStringProperty(String name); Calendar getDateProperty(String name); void removeProperty(String name); static final String TITLE; static final String CREATION_DATE; static final String LAST_MODIFIED; static final String LAST_ACTION; static final String AUTHOR_ID; static final String ACTIVATOR_ID; static final String TEMPLATE; static final String TEMPLATE_TYPE; static final String ACTIVATED; static final String DEFAULT_META_NODE; static final int ACTIVATION_STATUS_NOT_ACTIVATED; static final int ACTIVATION_STATUS_MODIFIED; static final int ACTIVATION_STATUS_ACTIVATED; } | @Test public void testGetIsActivated() throws RepositoryException { assertFalse(new MetaData(root).getIsActivated()); root.setProperty(NodeTypes.Activatable.ACTIVATION_STATUS, true); assertTrue(new MetaData(root).getIsActivated()); } |
MetaData { public int getActivationStatus() { if (getIsActivated()) { if (getModificationDate() != null && getModificationDate().after(getLastActionDate())) { return ACTIVATION_STATUS_MODIFIED; } return ACTIVATION_STATUS_ACTIVATED; } return ACTIVATION_STATUS_NOT_ACTIVATED; } protected MetaData(Node workingNode, AccessManager ignoredAccessManager); MetaData(Node workingNode); String getTitle(); void setTitle(String value); void setCreationDate(); Calendar getCreationDate(); void setActivated(); void setUnActivated(); boolean getIsActivated(); int getActivationStatus(); void setLastActivationActionDate(); Calendar getLastActionDate(); void setModificationDate(); Calendar getModificationDate(); String getAuthorId(); void setAuthorId(String value); String getActivatorId(); void setActivatorId(String value); String getTemplate(); void setTemplate(String value); void setProperty(String name, String value); void setProperty(String name, long value); void setProperty(String name, double value); void setProperty(String name, boolean value); void setProperty(String name, Calendar value); boolean getBooleanProperty(String name); double getDoubleProperty(String name); long getLongProperty(String name); String getStringProperty(String name); Calendar getDateProperty(String name); void removeProperty(String name); static final String TITLE; static final String CREATION_DATE; static final String LAST_MODIFIED; static final String LAST_ACTION; static final String AUTHOR_ID; static final String ACTIVATOR_ID; static final String TEMPLATE; static final String TEMPLATE_TYPE; static final String ACTIVATED; static final String DEFAULT_META_NODE; static final int ACTIVATION_STATUS_NOT_ACTIVATED; static final int ACTIVATION_STATUS_MODIFIED; static final int ACTIVATION_STATUS_ACTIVATED; } | @Test public void testGetActivationStatusReturnsNotActivatedWhenNotActivated() { assertEquals(NodeTypes.Activatable.ACTIVATION_STATUS_NOT_ACTIVATED, new MetaData(root).getActivationStatus()); } |
MetaData { public void setLastActivationActionDate() { Calendar value = new GregorianCalendar(TimeZone.getDefault()); setProperty(LAST_ACTION, value); } protected MetaData(Node workingNode, AccessManager ignoredAccessManager); MetaData(Node workingNode); String getTitle(); void setTitle(String value); void setCreationDate(); Calendar getCreationDate(); void setActivated(); void setUnActivated(); boolean getIsActivated(); int getActivationStatus(); void setLastActivationActionDate(); Calendar getLastActionDate(); void setModificationDate(); Calendar getModificationDate(); String getAuthorId(); void setAuthorId(String value); String getActivatorId(); void setActivatorId(String value); String getTemplate(); void setTemplate(String value); void setProperty(String name, String value); void setProperty(String name, long value); void setProperty(String name, double value); void setProperty(String name, boolean value); void setProperty(String name, Calendar value); boolean getBooleanProperty(String name); double getDoubleProperty(String name); long getLongProperty(String name); String getStringProperty(String name); Calendar getDateProperty(String name); void removeProperty(String name); static final String TITLE; static final String CREATION_DATE; static final String LAST_MODIFIED; static final String LAST_ACTION; static final String AUTHOR_ID; static final String ACTIVATOR_ID; static final String TEMPLATE; static final String TEMPLATE_TYPE; static final String ACTIVATED; static final String DEFAULT_META_NODE; static final int ACTIVATION_STATUS_NOT_ACTIVATED; static final int ACTIVATION_STATUS_MODIFIED; static final int ACTIVATION_STATUS_ACTIVATED; } | @Test public void testSetLastActivationActionDate() throws RepositoryException { assertFalse(root.hasProperty(NodeTypes.Activatable.LAST_ACTIVATED)); new MetaData(root).setLastActivationActionDate(); assertTrue(root.hasProperty(NodeTypes.Activatable.LAST_ACTIVATED)); } |
MetaData { public Calendar getLastActionDate() { return getDateProperty(LAST_ACTION); } protected MetaData(Node workingNode, AccessManager ignoredAccessManager); MetaData(Node workingNode); String getTitle(); void setTitle(String value); void setCreationDate(); Calendar getCreationDate(); void setActivated(); void setUnActivated(); boolean getIsActivated(); int getActivationStatus(); void setLastActivationActionDate(); Calendar getLastActionDate(); void setModificationDate(); Calendar getModificationDate(); String getAuthorId(); void setAuthorId(String value); String getActivatorId(); void setActivatorId(String value); String getTemplate(); void setTemplate(String value); void setProperty(String name, String value); void setProperty(String name, long value); void setProperty(String name, double value); void setProperty(String name, boolean value); void setProperty(String name, Calendar value); boolean getBooleanProperty(String name); double getDoubleProperty(String name); long getLongProperty(String name); String getStringProperty(String name); Calendar getDateProperty(String name); void removeProperty(String name); static final String TITLE; static final String CREATION_DATE; static final String LAST_MODIFIED; static final String LAST_ACTION; static final String AUTHOR_ID; static final String ACTIVATOR_ID; static final String TEMPLATE; static final String TEMPLATE_TYPE; static final String ACTIVATED; static final String DEFAULT_META_NODE; static final int ACTIVATION_STATUS_NOT_ACTIVATED; static final int ACTIVATION_STATUS_MODIFIED; static final int ACTIVATION_STATUS_ACTIVATED; } | @Test public void testGetLastActionDate() throws RepositoryException { assertFalse(root.hasProperty(NodeTypes.Activatable.LAST_ACTIVATED)); assertNull(new MetaData(root).getLastActionDate()); root.setProperty(NodeTypes.Activatable.LAST_ACTIVATED, Calendar.getInstance()); assertTrue(root.hasProperty(NodeTypes.Activatable.LAST_ACTIVATED)); assertNotNull(new MetaData(root).getLastActionDate()); } |
MetaData { public void setModificationDate() { Calendar value = new GregorianCalendar(TimeZone.getDefault()); setProperty(LAST_MODIFIED, value); } protected MetaData(Node workingNode, AccessManager ignoredAccessManager); MetaData(Node workingNode); String getTitle(); void setTitle(String value); void setCreationDate(); Calendar getCreationDate(); void setActivated(); void setUnActivated(); boolean getIsActivated(); int getActivationStatus(); void setLastActivationActionDate(); Calendar getLastActionDate(); void setModificationDate(); Calendar getModificationDate(); String getAuthorId(); void setAuthorId(String value); String getActivatorId(); void setActivatorId(String value); String getTemplate(); void setTemplate(String value); void setProperty(String name, String value); void setProperty(String name, long value); void setProperty(String name, double value); void setProperty(String name, boolean value); void setProperty(String name, Calendar value); boolean getBooleanProperty(String name); double getDoubleProperty(String name); long getLongProperty(String name); String getStringProperty(String name); Calendar getDateProperty(String name); void removeProperty(String name); static final String TITLE; static final String CREATION_DATE; static final String LAST_MODIFIED; static final String LAST_ACTION; static final String AUTHOR_ID; static final String ACTIVATOR_ID; static final String TEMPLATE; static final String TEMPLATE_TYPE; static final String ACTIVATED; static final String DEFAULT_META_NODE; static final int ACTIVATION_STATUS_NOT_ACTIVATED; static final int ACTIVATION_STATUS_MODIFIED; static final int ACTIVATION_STATUS_ACTIVATED; } | @Test public void testSetModificationDate() throws RepositoryException { assertFalse(root.hasProperty(NodeTypes.LastModified.LAST_MODIFIED)); new MetaData(root).setModificationDate(); assertTrue(root.hasProperty(NodeTypes.LastModified.LAST_MODIFIED)); } |
MetaData { public Calendar getModificationDate() { Calendar modDate = getDateProperty(LAST_MODIFIED); if (modDate == null) { modDate = getCreationDate(); } return modDate; } protected MetaData(Node workingNode, AccessManager ignoredAccessManager); MetaData(Node workingNode); String getTitle(); void setTitle(String value); void setCreationDate(); Calendar getCreationDate(); void setActivated(); void setUnActivated(); boolean getIsActivated(); int getActivationStatus(); void setLastActivationActionDate(); Calendar getLastActionDate(); void setModificationDate(); Calendar getModificationDate(); String getAuthorId(); void setAuthorId(String value); String getActivatorId(); void setActivatorId(String value); String getTemplate(); void setTemplate(String value); void setProperty(String name, String value); void setProperty(String name, long value); void setProperty(String name, double value); void setProperty(String name, boolean value); void setProperty(String name, Calendar value); boolean getBooleanProperty(String name); double getDoubleProperty(String name); long getLongProperty(String name); String getStringProperty(String name); Calendar getDateProperty(String name); void removeProperty(String name); static final String TITLE; static final String CREATION_DATE; static final String LAST_MODIFIED; static final String LAST_ACTION; static final String AUTHOR_ID; static final String ACTIVATOR_ID; static final String TEMPLATE; static final String TEMPLATE_TYPE; static final String ACTIVATED; static final String DEFAULT_META_NODE; static final int ACTIVATION_STATUS_NOT_ACTIVATED; static final int ACTIVATION_STATUS_MODIFIED; static final int ACTIVATION_STATUS_ACTIVATED; } | @Test public void testGetModificationDate() throws RepositoryException { assertFalse(root.hasProperty(NodeTypes.LastModified.LAST_MODIFIED)); assertNull(new MetaData(root).getModificationDate()); root.setProperty(NodeTypes.LastModified.LAST_MODIFIED, Calendar.getInstance()); assertTrue(root.hasProperty(NodeTypes.LastModified.LAST_MODIFIED)); assertNotNull(new MetaData(root).getModificationDate()); } |
MetaData { public String getAuthorId() { return getStringProperty(AUTHOR_ID); } protected MetaData(Node workingNode, AccessManager ignoredAccessManager); MetaData(Node workingNode); String getTitle(); void setTitle(String value); void setCreationDate(); Calendar getCreationDate(); void setActivated(); void setUnActivated(); boolean getIsActivated(); int getActivationStatus(); void setLastActivationActionDate(); Calendar getLastActionDate(); void setModificationDate(); Calendar getModificationDate(); String getAuthorId(); void setAuthorId(String value); String getActivatorId(); void setActivatorId(String value); String getTemplate(); void setTemplate(String value); void setProperty(String name, String value); void setProperty(String name, long value); void setProperty(String name, double value); void setProperty(String name, boolean value); void setProperty(String name, Calendar value); boolean getBooleanProperty(String name); double getDoubleProperty(String name); long getLongProperty(String name); String getStringProperty(String name); Calendar getDateProperty(String name); void removeProperty(String name); static final String TITLE; static final String CREATION_DATE; static final String LAST_MODIFIED; static final String LAST_ACTION; static final String AUTHOR_ID; static final String ACTIVATOR_ID; static final String TEMPLATE; static final String TEMPLATE_TYPE; static final String ACTIVATED; static final String DEFAULT_META_NODE; static final int ACTIVATION_STATUS_NOT_ACTIVATED; static final int ACTIVATION_STATUS_MODIFIED; static final int ACTIVATION_STATUS_ACTIVATED; } | @Test public void testGetAuthorId() throws RepositoryException { assertFalse(root.hasProperty(NodeTypes.LastModified.LAST_MODIFIED_BY)); assertEquals("", new MetaData(root).getAuthorId()); root.setProperty(NodeTypes.LastModified.LAST_MODIFIED_BY, "superuser"); assertTrue(root.hasProperty(NodeTypes.LastModified.LAST_MODIFIED_BY)); assertNotNull(new MetaData(root).getAuthorId()); } |
MetaData { public void setAuthorId(String value) { setProperty(AUTHOR_ID, value); } protected MetaData(Node workingNode, AccessManager ignoredAccessManager); MetaData(Node workingNode); String getTitle(); void setTitle(String value); void setCreationDate(); Calendar getCreationDate(); void setActivated(); void setUnActivated(); boolean getIsActivated(); int getActivationStatus(); void setLastActivationActionDate(); Calendar getLastActionDate(); void setModificationDate(); Calendar getModificationDate(); String getAuthorId(); void setAuthorId(String value); String getActivatorId(); void setActivatorId(String value); String getTemplate(); void setTemplate(String value); void setProperty(String name, String value); void setProperty(String name, long value); void setProperty(String name, double value); void setProperty(String name, boolean value); void setProperty(String name, Calendar value); boolean getBooleanProperty(String name); double getDoubleProperty(String name); long getLongProperty(String name); String getStringProperty(String name); Calendar getDateProperty(String name); void removeProperty(String name); static final String TITLE; static final String CREATION_DATE; static final String LAST_MODIFIED; static final String LAST_ACTION; static final String AUTHOR_ID; static final String ACTIVATOR_ID; static final String TEMPLATE; static final String TEMPLATE_TYPE; static final String ACTIVATED; static final String DEFAULT_META_NODE; static final int ACTIVATION_STATUS_NOT_ACTIVATED; static final int ACTIVATION_STATUS_MODIFIED; static final int ACTIVATION_STATUS_ACTIVATED; } | @Test public void testSetAuthorId() throws RepositoryException { assertFalse(root.hasProperty(NodeTypes.LastModified.LAST_MODIFIED_BY)); new MetaData(root).setAuthorId("superuser"); assertTrue(root.hasProperty(NodeTypes.LastModified.LAST_MODIFIED_BY)); } |
MetaData { public String getActivatorId() { return getStringProperty(ACTIVATOR_ID); } protected MetaData(Node workingNode, AccessManager ignoredAccessManager); MetaData(Node workingNode); String getTitle(); void setTitle(String value); void setCreationDate(); Calendar getCreationDate(); void setActivated(); void setUnActivated(); boolean getIsActivated(); int getActivationStatus(); void setLastActivationActionDate(); Calendar getLastActionDate(); void setModificationDate(); Calendar getModificationDate(); String getAuthorId(); void setAuthorId(String value); String getActivatorId(); void setActivatorId(String value); String getTemplate(); void setTemplate(String value); void setProperty(String name, String value); void setProperty(String name, long value); void setProperty(String name, double value); void setProperty(String name, boolean value); void setProperty(String name, Calendar value); boolean getBooleanProperty(String name); double getDoubleProperty(String name); long getLongProperty(String name); String getStringProperty(String name); Calendar getDateProperty(String name); void removeProperty(String name); static final String TITLE; static final String CREATION_DATE; static final String LAST_MODIFIED; static final String LAST_ACTION; static final String AUTHOR_ID; static final String ACTIVATOR_ID; static final String TEMPLATE; static final String TEMPLATE_TYPE; static final String ACTIVATED; static final String DEFAULT_META_NODE; static final int ACTIVATION_STATUS_NOT_ACTIVATED; static final int ACTIVATION_STATUS_MODIFIED; static final int ACTIVATION_STATUS_ACTIVATED; } | @Test public void testGetActivatorId() throws RepositoryException { assertFalse(root.hasProperty(NodeTypes.Activatable.LAST_ACTIVATED_BY)); assertEquals("", new MetaData(root).getActivatorId()); root.setProperty(NodeTypes.Activatable.LAST_ACTIVATED_BY, "superuser"); assertTrue(root.hasProperty(NodeTypes.Activatable.LAST_ACTIVATED_BY)); assertNotNull(new MetaData(root).getActivatorId()); } |
MetaData { public void setActivatorId(String value) { setProperty(ACTIVATOR_ID, value); } protected MetaData(Node workingNode, AccessManager ignoredAccessManager); MetaData(Node workingNode); String getTitle(); void setTitle(String value); void setCreationDate(); Calendar getCreationDate(); void setActivated(); void setUnActivated(); boolean getIsActivated(); int getActivationStatus(); void setLastActivationActionDate(); Calendar getLastActionDate(); void setModificationDate(); Calendar getModificationDate(); String getAuthorId(); void setAuthorId(String value); String getActivatorId(); void setActivatorId(String value); String getTemplate(); void setTemplate(String value); void setProperty(String name, String value); void setProperty(String name, long value); void setProperty(String name, double value); void setProperty(String name, boolean value); void setProperty(String name, Calendar value); boolean getBooleanProperty(String name); double getDoubleProperty(String name); long getLongProperty(String name); String getStringProperty(String name); Calendar getDateProperty(String name); void removeProperty(String name); static final String TITLE; static final String CREATION_DATE; static final String LAST_MODIFIED; static final String LAST_ACTION; static final String AUTHOR_ID; static final String ACTIVATOR_ID; static final String TEMPLATE; static final String TEMPLATE_TYPE; static final String ACTIVATED; static final String DEFAULT_META_NODE; static final int ACTIVATION_STATUS_NOT_ACTIVATED; static final int ACTIVATION_STATUS_MODIFIED; static final int ACTIVATION_STATUS_ACTIVATED; } | @Test public void testSetActivatorId() throws RepositoryException { assertFalse(root.hasProperty(NodeTypes.Activatable.LAST_ACTIVATED_BY)); new MetaData(root).setActivatorId("superuser"); assertTrue(root.hasProperty(NodeTypes.Activatable.LAST_ACTIVATED_BY)); } |
MetaData { public String getTemplate() { return getStringProperty(TEMPLATE); } protected MetaData(Node workingNode, AccessManager ignoredAccessManager); MetaData(Node workingNode); String getTitle(); void setTitle(String value); void setCreationDate(); Calendar getCreationDate(); void setActivated(); void setUnActivated(); boolean getIsActivated(); int getActivationStatus(); void setLastActivationActionDate(); Calendar getLastActionDate(); void setModificationDate(); Calendar getModificationDate(); String getAuthorId(); void setAuthorId(String value); String getActivatorId(); void setActivatorId(String value); String getTemplate(); void setTemplate(String value); void setProperty(String name, String value); void setProperty(String name, long value); void setProperty(String name, double value); void setProperty(String name, boolean value); void setProperty(String name, Calendar value); boolean getBooleanProperty(String name); double getDoubleProperty(String name); long getLongProperty(String name); String getStringProperty(String name); Calendar getDateProperty(String name); void removeProperty(String name); static final String TITLE; static final String CREATION_DATE; static final String LAST_MODIFIED; static final String LAST_ACTION; static final String AUTHOR_ID; static final String ACTIVATOR_ID; static final String TEMPLATE; static final String TEMPLATE_TYPE; static final String ACTIVATED; static final String DEFAULT_META_NODE; static final int ACTIVATION_STATUS_NOT_ACTIVATED; static final int ACTIVATION_STATUS_MODIFIED; static final int ACTIVATION_STATUS_ACTIVATED; } | @Test public void testGetTemplate() throws RepositoryException { assertFalse(root.hasProperty(NodeTypes.Renderable.TEMPLATE)); assertEquals("", new MetaData(root).getTemplate()); root.setProperty(NodeTypes.Renderable.TEMPLATE, "samples:pages/main"); assertTrue(root.hasProperty(NodeTypes.Renderable.TEMPLATE)); assertNotNull(new MetaData(root).getTemplate()); } |
MetaData { public void setTemplate(String value) { setProperty(TEMPLATE, value); } protected MetaData(Node workingNode, AccessManager ignoredAccessManager); MetaData(Node workingNode); String getTitle(); void setTitle(String value); void setCreationDate(); Calendar getCreationDate(); void setActivated(); void setUnActivated(); boolean getIsActivated(); int getActivationStatus(); void setLastActivationActionDate(); Calendar getLastActionDate(); void setModificationDate(); Calendar getModificationDate(); String getAuthorId(); void setAuthorId(String value); String getActivatorId(); void setActivatorId(String value); String getTemplate(); void setTemplate(String value); void setProperty(String name, String value); void setProperty(String name, long value); void setProperty(String name, double value); void setProperty(String name, boolean value); void setProperty(String name, Calendar value); boolean getBooleanProperty(String name); double getDoubleProperty(String name); long getLongProperty(String name); String getStringProperty(String name); Calendar getDateProperty(String name); void removeProperty(String name); static final String TITLE; static final String CREATION_DATE; static final String LAST_MODIFIED; static final String LAST_ACTION; static final String AUTHOR_ID; static final String ACTIVATOR_ID; static final String TEMPLATE; static final String TEMPLATE_TYPE; static final String ACTIVATED; static final String DEFAULT_META_NODE; static final int ACTIVATION_STATUS_NOT_ACTIVATED; static final int ACTIVATION_STATUS_MODIFIED; static final int ACTIVATION_STATUS_ACTIVATED; } | @Test public void testSetTemplate() throws RepositoryException { assertFalse(root.hasProperty(NodeTypes.Renderable.TEMPLATE)); new MetaData(root).setTemplate("samples:pages/main"); assertTrue(root.hasProperty(NodeTypes.Renderable.TEMPLATE)); } |
MetaData { public String getStringProperty(String name) { try { final Property property = getJCRProperty(name); if (property != null) { return property.getString(); } } catch (RepositoryException re) { log.error(re.getMessage(), re); } return StringUtils.EMPTY; } protected MetaData(Node workingNode, AccessManager ignoredAccessManager); MetaData(Node workingNode); String getTitle(); void setTitle(String value); void setCreationDate(); Calendar getCreationDate(); void setActivated(); void setUnActivated(); boolean getIsActivated(); int getActivationStatus(); void setLastActivationActionDate(); Calendar getLastActionDate(); void setModificationDate(); Calendar getModificationDate(); String getAuthorId(); void setAuthorId(String value); String getActivatorId(); void setActivatorId(String value); String getTemplate(); void setTemplate(String value); void setProperty(String name, String value); void setProperty(String name, long value); void setProperty(String name, double value); void setProperty(String name, boolean value); void setProperty(String name, Calendar value); boolean getBooleanProperty(String name); double getDoubleProperty(String name); long getLongProperty(String name); String getStringProperty(String name); Calendar getDateProperty(String name); void removeProperty(String name); static final String TITLE; static final String CREATION_DATE; static final String LAST_MODIFIED; static final String LAST_ACTION; static final String AUTHOR_ID; static final String ACTIVATOR_ID; static final String TEMPLATE; static final String TEMPLATE_TYPE; static final String ACTIVATED; static final String DEFAULT_META_NODE; static final int ACTIVATION_STATUS_NOT_ACTIVATED; static final int ACTIVATION_STATUS_MODIFIED; static final int ACTIVATION_STATUS_ACTIVATED; } | @Test public void testGetStringProperty() throws RepositoryException { final String value = "value"; final MetaData md = new MetaData(root); md.setProperty(MetaData.TEMPLATE, value); final String result = md.getStringProperty(MetaData.TEMPLATE); assertEquals(value, result); assertTrue(root.hasProperty(NodeTypes.Renderable.TEMPLATE)); }
@Test(expected = IllegalArgumentException.class) public void testGetStringPropertyWithUnsupportedName() { new MetaData(root).getStringProperty("foo"); }
@Test(expected = IllegalArgumentException.class) public void testGetStringPropertyWithUnsupportedTitleProperty() { new MetaData(root).getStringProperty("mgnl:title"); }
@Test(expected = IllegalArgumentException.class) public void testGetStringPropertyWithUnsupportedTemplateTypeProperty() { new MetaData(root).getStringProperty("mgnl:templatetype"); } |
MetaData { public void setProperty(String name, String value) { setJCRProperty(name, value); } protected MetaData(Node workingNode, AccessManager ignoredAccessManager); MetaData(Node workingNode); String getTitle(); void setTitle(String value); void setCreationDate(); Calendar getCreationDate(); void setActivated(); void setUnActivated(); boolean getIsActivated(); int getActivationStatus(); void setLastActivationActionDate(); Calendar getLastActionDate(); void setModificationDate(); Calendar getModificationDate(); String getAuthorId(); void setAuthorId(String value); String getActivatorId(); void setActivatorId(String value); String getTemplate(); void setTemplate(String value); void setProperty(String name, String value); void setProperty(String name, long value); void setProperty(String name, double value); void setProperty(String name, boolean value); void setProperty(String name, Calendar value); boolean getBooleanProperty(String name); double getDoubleProperty(String name); long getLongProperty(String name); String getStringProperty(String name); Calendar getDateProperty(String name); void removeProperty(String name); static final String TITLE; static final String CREATION_DATE; static final String LAST_MODIFIED; static final String LAST_ACTION; static final String AUTHOR_ID; static final String ACTIVATOR_ID; static final String TEMPLATE; static final String TEMPLATE_TYPE; static final String ACTIVATED; static final String DEFAULT_META_NODE; static final int ACTIVATION_STATUS_NOT_ACTIVATED; static final int ACTIVATION_STATUS_MODIFIED; static final int ACTIVATION_STATUS_ACTIVATED; } | @Test(expected = IllegalArgumentException.class) public void testSetStringPropertyWithUnsupportedName() { new MetaData(root).setProperty("foo", "bar"); }
@Test(expected = IllegalArgumentException.class) public void testSetStringPropertyWithUnsupportedTitleProperty() { new MetaData(root).setProperty("mgnl:title", "bar"); }
@Test(expected = IllegalArgumentException.class) public void testSetStringPropertyWithUnsupportedTemplateTypeProperty() { new MetaData(root).setProperty("mgnl:templatetype", "bar"); } |
MetaData { public void removeProperty(String name) throws PathNotFoundException, RepositoryException { this.node.getProperty(this.getInternalPropertyName(name)).remove(); } protected MetaData(Node workingNode, AccessManager ignoredAccessManager); MetaData(Node workingNode); String getTitle(); void setTitle(String value); void setCreationDate(); Calendar getCreationDate(); void setActivated(); void setUnActivated(); boolean getIsActivated(); int getActivationStatus(); void setLastActivationActionDate(); Calendar getLastActionDate(); void setModificationDate(); Calendar getModificationDate(); String getAuthorId(); void setAuthorId(String value); String getActivatorId(); void setActivatorId(String value); String getTemplate(); void setTemplate(String value); void setProperty(String name, String value); void setProperty(String name, long value); void setProperty(String name, double value); void setProperty(String name, boolean value); void setProperty(String name, Calendar value); boolean getBooleanProperty(String name); double getDoubleProperty(String name); long getLongProperty(String name); String getStringProperty(String name); Calendar getDateProperty(String name); void removeProperty(String name); static final String TITLE; static final String CREATION_DATE; static final String LAST_MODIFIED; static final String LAST_ACTION; static final String AUTHOR_ID; static final String ACTIVATOR_ID; static final String TEMPLATE; static final String TEMPLATE_TYPE; static final String ACTIVATED; static final String DEFAULT_META_NODE; static final int ACTIVATION_STATUS_NOT_ACTIVATED; static final int ACTIVATION_STATUS_MODIFIED; static final int ACTIVATION_STATUS_ACTIVATED; } | @Test public void testRemoveProperty() throws RepositoryException { root.setProperty(NodeTypes.Renderable.TEMPLATE, "samples:pages/main"); new MetaData(root).removeProperty(MetaData.TEMPLATE); assertFalse(root.hasProperty(NodeTypes.Renderable.TEMPLATE)); }
@Test(expected = IllegalArgumentException.class) public void testRemovePropertyWithUnsupportedProperty() throws RepositoryException { new MetaData(root).removeProperty(MetaData.TEMPLATE_TYPE); } |
Path { public static boolean isAbsolute(String path) { if (path == null) { return false; } if (path.startsWith("/") || path.startsWith(File.separator)) { return true; } if (path.length() >= 3 && Character.isLetter(path.charAt(0)) && path.charAt(1) == ':') { return true; } return false; } private Path(); static String getCacheDirectoryPath(); static File getCacheDirectory(); static String getTempDirectoryPath(); static File getTempDirectory(); static String getHistoryFilePath(); static File getHistoryFile(); static String getRepositoriesConfigFilePath(); static File getRepositoriesConfigFile(); static File getAppRootDir(); static String getAbsoluteFileSystemPath(String path); static String getUniqueLabel(HierarchyManager hierarchyManager, String parent, String label); static String getUniqueLabel(Session session, String parent, String label); static String getUniqueLabel(Content parent, String label); static boolean isAbsolute(String path); static String getValidatedLabel(String label); static String getValidatedLabel(String label, String charset); static boolean isCharValid(int charCode, String charset); static String getAbsolutePath(String path, String label); static String getAbsolutePath(String path); @Deprecated static String getNodePath(String path, String label); @Deprecated static String getNodePath(String path); @Deprecated static String getParentPath(String path); static final String SELECTOR_DELIMITER; } | @Test public void testIsAbsolute() { assertTrue(Path.isAbsolute("/test")); assertTrue(Path.isAbsolute("d:/test")); assertTrue(Path.isAbsolute(File.separator + "test")); assertFalse(Path.isAbsolute("test")); } |
Path { public static boolean isCharValid(int charCode, String charset) { if ("UTF-8".equals(charset)) { if (charCode != 32 && charCode != '[' && charCode != ']' && charCode != '*' && charCode != '"' && charCode != ':' && charCode != 92 && charCode != 39 && charCode != ';' && charCode != '/' && charCode != '?' && charCode != '+' && charCode != '%' && charCode != '!' && charCode != '#' && charCode != '@' && charCode != '&' && charCode != '=') { return true; } } else { if (((charCode >= 48) && (charCode <= 57)) || ((charCode >= 65) && (charCode <= 90)) || ((charCode >= 97) && (charCode <= 122)) || charCode == 45 || charCode == 46 || charCode == 95) { return true; } } return false; } private Path(); static String getCacheDirectoryPath(); static File getCacheDirectory(); static String getTempDirectoryPath(); static File getTempDirectory(); static String getHistoryFilePath(); static File getHistoryFile(); static String getRepositoriesConfigFilePath(); static File getRepositoriesConfigFile(); static File getAppRootDir(); static String getAbsoluteFileSystemPath(String path); static String getUniqueLabel(HierarchyManager hierarchyManager, String parent, String label); static String getUniqueLabel(Session session, String parent, String label); static String getUniqueLabel(Content parent, String label); static boolean isAbsolute(String path); static String getValidatedLabel(String label); static String getValidatedLabel(String label, String charset); static boolean isCharValid(int charCode, String charset); static String getAbsolutePath(String path, String label); static String getAbsolutePath(String path); @Deprecated static String getNodePath(String path, String label); @Deprecated static String getNodePath(String path); @Deprecated static String getParentPath(String path); static final String SELECTOR_DELIMITER; } | @Test public void testIsCharValid() throws Exception{ assertTrue(Path.isCharValid('.', null)); assertFalse(Path.isCharValid(32, null)); assertFalse(Path.isCharValid('[', null)); assertFalse(Path.isCharValid(']', null)); assertFalse(Path.isCharValid('*', null)); assertFalse(Path.isCharValid('"', null)); assertFalse(Path.isCharValid('\'', null)); assertFalse(Path.isCharValid(':', null)); } |
Path { public static String getValidatedLabel(String label) { String charset = StringUtils.EMPTY; if ((SystemProperty.getBooleanProperty(SystemProperty.MAGNOLIA_UTF8_ENABLED))) { charset = "UTF-8"; } return getValidatedLabel(label, charset); } private Path(); static String getCacheDirectoryPath(); static File getCacheDirectory(); static String getTempDirectoryPath(); static File getTempDirectory(); static String getHistoryFilePath(); static File getHistoryFile(); static String getRepositoriesConfigFilePath(); static File getRepositoriesConfigFile(); static File getAppRootDir(); static String getAbsoluteFileSystemPath(String path); static String getUniqueLabel(HierarchyManager hierarchyManager, String parent, String label); static String getUniqueLabel(Session session, String parent, String label); static String getUniqueLabel(Content parent, String label); static boolean isAbsolute(String path); static String getValidatedLabel(String label); static String getValidatedLabel(String label, String charset); static boolean isCharValid(int charCode, String charset); static String getAbsolutePath(String path, String label); static String getAbsolutePath(String path); @Deprecated static String getNodePath(String path, String label); @Deprecated static String getNodePath(String path); @Deprecated static String getParentPath(String path); static final String SELECTOR_DELIMITER; } | @Test public void testGetValidatedLabel() throws Exception { assertEquals("f",Path.getValidatedLabel("f", null)); assertEquals("fo",Path.getValidatedLabel("fo", null)); assertEquals("foo",Path.getValidatedLabel("foo", null)); assertEquals("foo.bar",Path.getValidatedLabel("foo.bar", null)); assertEquals("foo..bar",Path.getValidatedLabel("foo..bar", null)); assertEquals("-foo",Path.getValidatedLabel(".foo", null)); assertEquals("-.foo",Path.getValidatedLabel("..foo", null)); assertEquals("f-oo",Path.getValidatedLabel("f$oo", null)); assertEquals("f-oo",Path.getValidatedLabel("f*oo", null)); assertEquals("f-oo",Path.getValidatedLabel("f[oo", null)); assertEquals("f-oo",Path.getValidatedLabel("f]oo", null)); assertEquals("f-oo",Path.getValidatedLabel("f;oo", null)); assertEquals("f-oo",Path.getValidatedLabel("f:oo", null)); assertEquals("f-oo",Path.getValidatedLabel("f\"oo", null)); assertEquals("f-oo",Path.getValidatedLabel("f'oo", null)); assertEquals("f-oo",Path.getValidatedLabel("f#oo", null)); assertEquals("f-oo",Path.getValidatedLabel("f!oo", null)); assertEquals("f-oo",Path.getValidatedLabel("f+oo", null)); assertEquals("f-oo",Path.getValidatedLabel("f?oo", null)); assertEquals("f-oo",Path.getValidatedLabel("f/oo", null)); assertEquals("f-oo",Path.getValidatedLabel("f%oo", null)); assertEquals("f-oo",Path.getValidatedLabel("f oo", null)); assertEquals("f-oo",Path.getValidatedLabel("f-oo", null)); assertEquals("f_oo",Path.getValidatedLabel("f_oo", null)); assertEquals("0",Path.getValidatedLabel("0", null)); assertEquals("0foo",Path.getValidatedLabel("0foo", null)); assertEquals("123",Path.getValidatedLabel("123", null)); assertEquals("foo0",Path.getValidatedLabel("foo0", null)); assertEquals("FOO",Path.getValidatedLabel("FOO", null)); assertEquals("untitled",Path.getValidatedLabel(null, null)); assertEquals("untitled",Path.getValidatedLabel("", null)); assertEquals("----",Path.getValidatedLabel(" ", null)); } |
Path { public static String getAbsoluteFileSystemPath(String path) { if (isAbsolute(path)) { return path; } return new File(getAppRootDir(), path).getAbsolutePath(); } private Path(); static String getCacheDirectoryPath(); static File getCacheDirectory(); static String getTempDirectoryPath(); static File getTempDirectory(); static String getHistoryFilePath(); static File getHistoryFile(); static String getRepositoriesConfigFilePath(); static File getRepositoriesConfigFile(); static File getAppRootDir(); static String getAbsoluteFileSystemPath(String path); static String getUniqueLabel(HierarchyManager hierarchyManager, String parent, String label); static String getUniqueLabel(Session session, String parent, String label); static String getUniqueLabel(Content parent, String label); static boolean isAbsolute(String path); static String getValidatedLabel(String label); static String getValidatedLabel(String label, String charset); static boolean isCharValid(int charCode, String charset); static String getAbsolutePath(String path, String label); static String getAbsolutePath(String path); @Deprecated static String getNodePath(String path, String label); @Deprecated static String getNodePath(String path); @Deprecated static String getParentPath(String path); static final String SELECTOR_DELIMITER; } | @Test public void testGetAbsoluteFileSystemPathReturnsArgumentIfPathIsAbsolute() throws Exception { String absPath = "/foo/bar"; String returnedPath = Path.getAbsoluteFileSystemPath(absPath); assertEquals(absPath, returnedPath); } |
VersionedNode extends PropertyAndChildWrappingNodeWrapper implements Version { @Override public Property wrapProperty(Property property) { return new DelegatePropertyWrapper(property) { @Override public String getPath() throws RepositoryException { return VersionedNode.this.getPath() + "/" + getName(); } }; } VersionedNode(Version versionedNode, Node baseNode); @Override int getDepth(); @Override Item getAncestor(int depth); Version unwrap(); @Override VersionHistory getContainingHistory(); @Override Calendar getCreated(); @Override Node getFrozenNode(); @Override Version getLinearPredecessor(); @Override Version getLinearSuccessor(); @Override Version[] getPredecessors(); @Override Version[] getSuccessors(); @Override Node wrapNode(Node node); @Override Property wrapProperty(Property property); @Override String getPath(); @Override Node getParent(); @Override boolean isNodeType(String nodeTypeName); @Override NodeType getPrimaryNodeType(); Node getBaseNode(); @Override Session getSession(); } | @Test public void testWrapProperty() throws Exception { final Version v = mock(Version.class); final Node baseNode = mock(Node.class); when(baseNode.getPath()).thenReturn("baseNodePath"); final VersionedNode vn = new VersionedNode(v, baseNode); final Property property2Wrap = mock(Property.class); when(property2Wrap.getName()).thenReturn("nameOfProperty2Wrap"); final Property wrapped = vn.wrapProperty(property2Wrap); final String path = wrapped.getPath(); assertEquals("baseNodePath/nameOfProperty2Wrap", path); } |
BaseVersionManager { protected Session getSession() throws LoginException, RepositoryException { return MgnlContext.getSystemContext().getJCRSession(VersionManager.VERSION_WORKSPACE); } synchronized Version addVersion(Node node); synchronized Version addVersion(final Node node, final Rule rule); abstract boolean isInvalidMaxVersions(); synchronized Node getVersionedNode(Node node); abstract void setMaxVersionHistory(Node node); synchronized VersionHistory getVersionHistory(Node node); synchronized Version getVersion(Node node, String name); Version getBaseVersion(Node node); synchronized VersionIterator getAllVersions(Node node); @Deprecated synchronized void restore(Content node, Version version, boolean removeExisting); synchronized void restore(final Node node, Version version, boolean removeExisting); synchronized void removeVersionHistory(final Node node); static final String VERSION_WORKSPACE; static final String TMP_REFERENCED_NODES; static final String PROPERTY_RULE; } | @Test public void testUseSystemSessionToRetrieveVersions() throws RepositoryException { Session session = MgnlContext.getSystemContext().getJCRSession(RepositoryConstants.VERSION_STORE); VersionManager versionMan = VersionManager.getInstance(); assertSame(session, versionMan.getSession()); } |
DefaultContent extends AbstractContent { @Override public void addMixin(String type) throws RepositoryException { if (!this.node.canAddMixin(type)) { log.debug("Node - " + this.node.getPath() + " does not allow mixin type - " + type); } try { this.node.addMixin(type); } catch (Exception e) { log.error("Failed to add mixin type - " + type + " to a node " + this.node.getPath()); } } protected DefaultContent(); protected DefaultContent(Node rootNode, String path); DefaultContent(Node node); protected DefaultContent(Node rootNode, String path, String contentType); @Override Content getContent(String name); @Override Content createContent(String name, String contentType); @Override boolean hasNodeData(String name); @Override NodeData newNodeDataInstance(String name, int type, boolean createIfNotExisting); @Override MetaData getMetaData(); @Override String getName(); @Override Collection<Content> getChildren(ContentFilter filter, String namePattern, Comparator<Content> orderCriteria); @Override Collection<NodeData> getNodeDataCollection(String namePattern); @Override boolean hasContent(String name); @Override String getHandle(); @Override Content getParent(); @Override Content getAncestor(int level); @Override Collection<Content> getAncestors(); @Override int getLevel(); @Override void orderBefore(String srcName, String beforeName); @Override int getIndex(); @Override Node getJCRNode(); @Override boolean isNodeType(String type); @Override NodeType getNodeType(); @Override String getNodeTypeName(); @Override ItemType getItemType(); @Override void restore(String versionName, boolean removeExisting); @Override void restore(Version version, boolean removeExisting); @Override void restore(Version version, String relPath, boolean removeExisting); @Override void restoreByLabel(String versionLabel, boolean removeExisting); @Override Version addVersion(); @Override Version addVersion(Rule rule); BinaryNodeData addBinaryNodeData(String name); @Override boolean isModified(); @Override VersionHistory getVersionHistory(); @Override VersionIterator getAllVersions(); @Override ContentVersion getBaseVersion(); @Override ContentVersion getVersionedContent(Version version); @Override ContentVersion getVersionedContent(String versionName); @Override void removeVersionHistory(); @Override void save(); @Override void delete(); @Override void refresh(boolean keepChanges); @Override String getUUID(); @Override void addMixin(String type); @Override void removeMixin(String type); @Override NodeType[] getMixinNodeTypes(); @Override Lock lock(boolean isDeep, boolean isSessionScoped); @Override Lock lock(boolean isDeep, boolean isSessionScoped, long yieldFor); @Override Lock getLock(); @Override void unlock(); @Override boolean holdsLock(); @Override boolean isLocked(); @Override boolean hasMetaData(); @Override boolean hasMixin(String mixinName); @Override HierarchyManager getHierarchyManager(); @Override Workspace getWorkspace(); @Override boolean equals(Object obj); } | @Test public void testAddMixin() throws IOException, RepositoryException{ final Content content = getTestContent(); final String repoName = content.getWorkspace().getName(); final String mixDeleted = "mgnl:deleted"; final Provider repoProvider = ContentRepository.getRepositoryProvider(repoName); final String mgnlMixDeleted = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<nodeTypes" + " xmlns:rep=\"internal\"" + " xmlns:nt=\"http: + " xmlns:mgnl=\"http: + "\" isMixin=\"true\" hasOrderableChildNodes=\"true\" primaryItemName=\"\">" + "<supertypes>" + "<supertype>nt:base</supertype>" + "</supertypes>" + "</nodeType>" + "</nodeTypes>"; try { repoProvider.registerNodeTypes(new ByteArrayInputStream(mgnlMixDeleted.getBytes())); } catch (RepositoryException e) { } assertTrue(content.getJCRNode().canAddMixin(mixDeleted)); content.addMixin(mixDeleted); } |
DefaultContent extends AbstractContent { @Override public void save() throws RepositoryException { this.node.save(); } protected DefaultContent(); protected DefaultContent(Node rootNode, String path); DefaultContent(Node node); protected DefaultContent(Node rootNode, String path, String contentType); @Override Content getContent(String name); @Override Content createContent(String name, String contentType); @Override boolean hasNodeData(String name); @Override NodeData newNodeDataInstance(String name, int type, boolean createIfNotExisting); @Override MetaData getMetaData(); @Override String getName(); @Override Collection<Content> getChildren(ContentFilter filter, String namePattern, Comparator<Content> orderCriteria); @Override Collection<NodeData> getNodeDataCollection(String namePattern); @Override boolean hasContent(String name); @Override String getHandle(); @Override Content getParent(); @Override Content getAncestor(int level); @Override Collection<Content> getAncestors(); @Override int getLevel(); @Override void orderBefore(String srcName, String beforeName); @Override int getIndex(); @Override Node getJCRNode(); @Override boolean isNodeType(String type); @Override NodeType getNodeType(); @Override String getNodeTypeName(); @Override ItemType getItemType(); @Override void restore(String versionName, boolean removeExisting); @Override void restore(Version version, boolean removeExisting); @Override void restore(Version version, String relPath, boolean removeExisting); @Override void restoreByLabel(String versionLabel, boolean removeExisting); @Override Version addVersion(); @Override Version addVersion(Rule rule); BinaryNodeData addBinaryNodeData(String name); @Override boolean isModified(); @Override VersionHistory getVersionHistory(); @Override VersionIterator getAllVersions(); @Override ContentVersion getBaseVersion(); @Override ContentVersion getVersionedContent(Version version); @Override ContentVersion getVersionedContent(String versionName); @Override void removeVersionHistory(); @Override void save(); @Override void delete(); @Override void refresh(boolean keepChanges); @Override String getUUID(); @Override void addMixin(String type); @Override void removeMixin(String type); @Override NodeType[] getMixinNodeTypes(); @Override Lock lock(boolean isDeep, boolean isSessionScoped); @Override Lock lock(boolean isDeep, boolean isSessionScoped, long yieldFor); @Override Lock getLock(); @Override void unlock(); @Override boolean holdsLock(); @Override boolean isLocked(); @Override boolean hasMetaData(); @Override boolean hasMixin(String mixinName); @Override HierarchyManager getHierarchyManager(); @Override Workspace getWorkspace(); @Override boolean equals(Object obj); } | @Test public void testCreatingAndReadingABinaryNodeData() throws IOException, RepositoryException{ Content content = getTestContent(); String binaryContent = "the content"; NodeData nodeData = content.createNodeData("nd2", PropertyType.BINARY); nodeData.setValue(IOUtils.toInputStream(binaryContent)); nodeData.setAttribute(FileProperties.PROPERTY_CONTENTTYPE, "text/plain"); nodeData.setAttribute(FileProperties.PROPERTY_LASTMODIFIED, Calendar.getInstance()); content.save(); nodeData = content.getNodeData("nd2"); assertEquals(binaryContent, IOUtils.toString(nodeData.getStream())); } |
DefaultContent extends AbstractContent { @Override public String getName() { try { return this.node.getName(); } catch (RepositoryException e) { log.error(e.getMessage(), e); } return StringUtils.EMPTY; } protected DefaultContent(); protected DefaultContent(Node rootNode, String path); DefaultContent(Node node); protected DefaultContent(Node rootNode, String path, String contentType); @Override Content getContent(String name); @Override Content createContent(String name, String contentType); @Override boolean hasNodeData(String name); @Override NodeData newNodeDataInstance(String name, int type, boolean createIfNotExisting); @Override MetaData getMetaData(); @Override String getName(); @Override Collection<Content> getChildren(ContentFilter filter, String namePattern, Comparator<Content> orderCriteria); @Override Collection<NodeData> getNodeDataCollection(String namePattern); @Override boolean hasContent(String name); @Override String getHandle(); @Override Content getParent(); @Override Content getAncestor(int level); @Override Collection<Content> getAncestors(); @Override int getLevel(); @Override void orderBefore(String srcName, String beforeName); @Override int getIndex(); @Override Node getJCRNode(); @Override boolean isNodeType(String type); @Override NodeType getNodeType(); @Override String getNodeTypeName(); @Override ItemType getItemType(); @Override void restore(String versionName, boolean removeExisting); @Override void restore(Version version, boolean removeExisting); @Override void restore(Version version, String relPath, boolean removeExisting); @Override void restoreByLabel(String versionLabel, boolean removeExisting); @Override Version addVersion(); @Override Version addVersion(Rule rule); BinaryNodeData addBinaryNodeData(String name); @Override boolean isModified(); @Override VersionHistory getVersionHistory(); @Override VersionIterator getAllVersions(); @Override ContentVersion getBaseVersion(); @Override ContentVersion getVersionedContent(Version version); @Override ContentVersion getVersionedContent(String versionName); @Override void removeVersionHistory(); @Override void save(); @Override void delete(); @Override void refresh(boolean keepChanges); @Override String getUUID(); @Override void addMixin(String type); @Override void removeMixin(String type); @Override NodeType[] getMixinNodeTypes(); @Override Lock lock(boolean isDeep, boolean isSessionScoped); @Override Lock lock(boolean isDeep, boolean isSessionScoped, long yieldFor); @Override Lock getLock(); @Override void unlock(); @Override boolean holdsLock(); @Override boolean isLocked(); @Override boolean hasMetaData(); @Override boolean hasMixin(String mixinName); @Override HierarchyManager getHierarchyManager(); @Override Workspace getWorkspace(); @Override boolean equals(Object obj); } | @Test public void testThatReadingANonExistingNodeDataReturnsAnEmptyNodeData() throws IOException, RepositoryException{ Content content = getTestContent(); NodeData nd = content.getNodeData("nirvana"); assertEquals("nirvana", nd.getName()); assertEquals("", nd.getString()); assertEquals(false, nd.getBoolean()); assertEquals(0, nd.getLong()); assertEquals("", nd.getAttribute("other")); } |
DefaultContent extends AbstractContent { @Override public void delete() throws RepositoryException { final String nodePath = Path.getAbsolutePath(this.node.getPath()); final String workspaceName = this.node.getSession().getWorkspace().getName(); log.debug("removing {} from {}", this.node.getPath(), workspaceName); final ItemType nodeType = this.getItemType(); if (!workspaceName.startsWith("mgnl")) { MgnlContext.doInSystemContext(new Op<Void, RepositoryException>() { @Override public Void exec() throws RepositoryException { try { final String uuid = node.getUUID(); Session session = MgnlContext.getJCRSession("mgnlVersion"); Node versionedNode = session.getNodeByIdentifier(uuid); log.debug("Located versioned node {}({})", uuid, nodePath); VersionHistory history = versionedNode.getVersionHistory(); log.debug("Removing versioned node {}({})", uuid, nodePath); versionedNode.remove(); session.save(); VersionIterator iter = history.getAllVersions(); iter.nextVersion(); while (iter.hasNext()) { Version version = iter.nextVersion(); log.debug("removing version {}", version.getName()); history.removeVersion(version.getName()); } } catch (ItemNotFoundException e) { } catch (UnsupportedRepositoryOperationException e) { } return null; } }); } this.node.remove(); AuditLoggingUtil.log(AuditLoggingUtil.ACTION_DELETE, workspaceName, nodeType, nodePath); } protected DefaultContent(); protected DefaultContent(Node rootNode, String path); DefaultContent(Node node); protected DefaultContent(Node rootNode, String path, String contentType); @Override Content getContent(String name); @Override Content createContent(String name, String contentType); @Override boolean hasNodeData(String name); @Override NodeData newNodeDataInstance(String name, int type, boolean createIfNotExisting); @Override MetaData getMetaData(); @Override String getName(); @Override Collection<Content> getChildren(ContentFilter filter, String namePattern, Comparator<Content> orderCriteria); @Override Collection<NodeData> getNodeDataCollection(String namePattern); @Override boolean hasContent(String name); @Override String getHandle(); @Override Content getParent(); @Override Content getAncestor(int level); @Override Collection<Content> getAncestors(); @Override int getLevel(); @Override void orderBefore(String srcName, String beforeName); @Override int getIndex(); @Override Node getJCRNode(); @Override boolean isNodeType(String type); @Override NodeType getNodeType(); @Override String getNodeTypeName(); @Override ItemType getItemType(); @Override void restore(String versionName, boolean removeExisting); @Override void restore(Version version, boolean removeExisting); @Override void restore(Version version, String relPath, boolean removeExisting); @Override void restoreByLabel(String versionLabel, boolean removeExisting); @Override Version addVersion(); @Override Version addVersion(Rule rule); BinaryNodeData addBinaryNodeData(String name); @Override boolean isModified(); @Override VersionHistory getVersionHistory(); @Override VersionIterator getAllVersions(); @Override ContentVersion getBaseVersion(); @Override ContentVersion getVersionedContent(Version version); @Override ContentVersion getVersionedContent(String versionName); @Override void removeVersionHistory(); @Override void save(); @Override void delete(); @Override void refresh(boolean keepChanges); @Override String getUUID(); @Override void addMixin(String type); @Override void removeMixin(String type); @Override NodeType[] getMixinNodeTypes(); @Override Lock lock(boolean isDeep, boolean isSessionScoped); @Override Lock lock(boolean isDeep, boolean isSessionScoped, long yieldFor); @Override Lock getLock(); @Override void unlock(); @Override boolean holdsLock(); @Override boolean isLocked(); @Override boolean hasMetaData(); @Override boolean hasMixin(String mixinName); @Override HierarchyManager getHierarchyManager(); @Override Workspace getWorkspace(); @Override boolean equals(Object obj); } | @Test public void testDelete() throws Exception { final Content content = getTestContent(); final String uuid = content.getUUID(); final Content parent = content.getParent(); content.addVersion(); Content versionedContent = MgnlContext.getHierarchyManager("mgnlVersion").getContentByUUID(uuid); assertNotNull(versionedContent); VersionHistory history = versionedContent.getJCRNode().getVersionHistory(); VersionIterator versions = content.getAllVersions(); assertNotNull(versions.nextVersion()); assertNotNull(versions.nextVersion()); content.delete(); parent.save(); try { MgnlContext.getHierarchyManager("mgnlVersion").getContentByUUID(uuid); fail("versioned copy should have been deleted but was not."); } catch (ItemNotFoundException e) { } try { history.getVersionLabels(); fail("version history should have been invalidated by JR after manually deleting all versions except root and referencing content"); } catch (RepositoryException e) { } } |
DefaultContent extends AbstractContent { @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof DefaultContent)) { return false; } DefaultContent otherContent = (DefaultContent) obj; return getJCRNode().equals(otherContent.getJCRNode()); } protected DefaultContent(); protected DefaultContent(Node rootNode, String path); DefaultContent(Node node); protected DefaultContent(Node rootNode, String path, String contentType); @Override Content getContent(String name); @Override Content createContent(String name, String contentType); @Override boolean hasNodeData(String name); @Override NodeData newNodeDataInstance(String name, int type, boolean createIfNotExisting); @Override MetaData getMetaData(); @Override String getName(); @Override Collection<Content> getChildren(ContentFilter filter, String namePattern, Comparator<Content> orderCriteria); @Override Collection<NodeData> getNodeDataCollection(String namePattern); @Override boolean hasContent(String name); @Override String getHandle(); @Override Content getParent(); @Override Content getAncestor(int level); @Override Collection<Content> getAncestors(); @Override int getLevel(); @Override void orderBefore(String srcName, String beforeName); @Override int getIndex(); @Override Node getJCRNode(); @Override boolean isNodeType(String type); @Override NodeType getNodeType(); @Override String getNodeTypeName(); @Override ItemType getItemType(); @Override void restore(String versionName, boolean removeExisting); @Override void restore(Version version, boolean removeExisting); @Override void restore(Version version, String relPath, boolean removeExisting); @Override void restoreByLabel(String versionLabel, boolean removeExisting); @Override Version addVersion(); @Override Version addVersion(Rule rule); BinaryNodeData addBinaryNodeData(String name); @Override boolean isModified(); @Override VersionHistory getVersionHistory(); @Override VersionIterator getAllVersions(); @Override ContentVersion getBaseVersion(); @Override ContentVersion getVersionedContent(Version version); @Override ContentVersion getVersionedContent(String versionName); @Override void removeVersionHistory(); @Override void save(); @Override void delete(); @Override void refresh(boolean keepChanges); @Override String getUUID(); @Override void addMixin(String type); @Override void removeMixin(String type); @Override NodeType[] getMixinNodeTypes(); @Override Lock lock(boolean isDeep, boolean isSessionScoped); @Override Lock lock(boolean isDeep, boolean isSessionScoped, long yieldFor); @Override Lock getLock(); @Override void unlock(); @Override boolean holdsLock(); @Override boolean isLocked(); @Override boolean hasMetaData(); @Override boolean hasMixin(String mixinName); @Override HierarchyManager getHierarchyManager(); @Override Workspace getWorkspace(); @Override boolean equals(Object obj); } | @Test public void testEquals() { Node node = new MockNode("test"); DefaultContent first = new DefaultContent(node); DefaultContent second = new DefaultContent(node); boolean result = first.equals(second); assertTrue(result); }
@Test public void testEqualsWithNull() { Node node = new MockNode("test"); DefaultContent first = new DefaultContent(node); boolean result = first.equals(null); assertFalse(result); }
@Test public void testEqualsWithWrongType() { Node node = new MockNode("test"); DefaultContent first = new DefaultContent(node); Object second = "second"; boolean result = first.equals(second); assertFalse(result); } |
ContentTypeFilter extends AbstractMgnlFilter { protected String setupContentTypeAndCharacterEncoding(String extension, HttpServletRequest request, HttpServletResponse response) { final String mimeType = MIMEMapping.getMIMETypeOrDefault(extension); final String characterEncoding = MIMEMapping.getContentEncodingOrDefault(mimeType); try { if (request.getCharacterEncoding() == null) { request.setCharacterEncoding(characterEncoding); } } catch (UnsupportedEncodingException e) { log.error("Can't set character encoding for the request (extension=" + extension + ",mimetype=" + mimeType + ")", e); } response.setCharacterEncoding(characterEncoding); response.setContentType(mimeType); return characterEncoding; } @Override void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain); } | @Test public void testFilterWithEmptyDefaultExtension() { filter.setupContentTypeAndCharacterEncoding("", request, response); verify(response).setCharacterEncoding("UTF-8"); verify(response).setContentType(null); } |
InstallFilter extends AbstractMgnlFilter { @Override public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { final Context originalContext = MgnlContext.hasInstance() ? MgnlContext.getInstance() : null; final InstallWebContext ctx = new InstallWebContext(); ctx.init(request, response, servletContext); MgnlContext.setInstance(ctx); try { final String contextPath = request.getContextPath(); response.setContentType("text/html"); final Writer out = response.getWriter(); final String uri = request.getRequestURI(); final ModuleManagerUI ui = moduleManager.getUI(); final String prefix = contextPath + ModuleManagerWebUI.INSTALLER_PATH; if (uri.startsWith(prefix)) { final String command = StringUtils.defaultIfEmpty(StringUtils.substringAfter(uri, prefix + "/"), null); final boolean installDone = ui.execute(out, command); if (installDone) { filterManager.startUsingConfiguredFilters(); request.getSession().invalidate(); response.sendRedirect(contextPath + "/"); } } else { response.sendRedirect(prefix); } } catch (ModuleManagementException e) { log.error(e.getMessage(), e); throw new RuntimeException(e); } finally { MgnlContext.release(); MgnlContext.setInstance(originalContext); } } InstallFilter(ModuleManager moduleManager, FilterManager filterManager); @Override void init(FilterConfig filterConfig); @Override void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain); } | @Test public void testExecutesCorrectCommandBasedOnURI() throws Exception { expect(req.getRequestURI()).andReturn("/test/.magnolia/installer/foo"); expect(ui.execute(writer, "foo")).andReturn(false); replay(moduleManager, ui, req, res, chain); final InstallFilter installFilter = new InstallFilter(moduleManager, null); installFilter.doFilter(req, res, chain); verify(moduleManager, ui, req, res, chain); }
@Test public void testPassesNullAsCommandIfNoneSpecifiedWithTrailingSlash() throws Exception { expect(req.getRequestURI()).andReturn("/test/.magnolia/installer/"); expect(ui.execute(writer, null)).andReturn(false); replay(moduleManager, ui, req, res, chain); final InstallFilter installFilter = new InstallFilter(moduleManager, null); installFilter.doFilter(req, res, chain); verify(moduleManager, ui, req, res, chain); }
@Test public void testPassesNullAsCommandIfNoneSpecified() throws Exception { expect(req.getRequestURI()).andReturn("/test/.magnolia/installer"); expect(ui.execute(writer, null)).andReturn(false); replay(moduleManager, ui, req, res, chain); final InstallFilter installFilter = new InstallFilter(moduleManager, null); installFilter.doFilter(req, res, chain); verify(moduleManager, ui, req, res, chain); } |
MultiChannelFilter extends OncePerRequestAbstractMgnlFilter { @Override public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { AggregationState aggregationState = MgnlContext.getAggregationState(); final Channel channel = new Channel(); channel.setName(resolveChannel(request)); aggregationState.setChannel(channel); chain.doFilter(request, response); } @Inject MultiChannelFilter(ChannelManager channelManager); @Override void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain); static String ENFORCE_CHANNEL_PARAMETER; } | @Test public void testALLGetsSetWhenThereIsNoResolver() throws Exception { when(request.getRequestURL()).thenReturn(new StringBuffer("http: filter.doFilter(request, response, chain); assertEquals(ChannelResolver.ALL, MgnlContext.getAggregationState().getChannel().getName()); }
@Test public void testChannelFromResolverGetsSet() throws Exception { final ChannelConfiguration unresolvedChannel = new ChannelConfiguration(); unresolvedChannel.setResolver(new TestChannelResolver(ChannelResolver.UNRESOLVED)); channelManager.addChannel(ChannelResolver.UNRESOLVED, unresolvedChannel); final ChannelConfiguration resolvedChannel = new ChannelConfiguration(); final String testChannel = "test"; resolvedChannel.setResolver(new TestChannelResolver(testChannel)); channelManager.addChannel(testChannel, resolvedChannel); when(request.getRequestURL()).thenReturn(new StringBuffer("http: filter.doFilter(request, response, chain); assertEquals(testChannel, MgnlContext.getAggregationState().getChannel().getName()); }
@Test public void testChannelParameterValueGetsSet() throws Exception { final ChannelConfiguration resolvedChannel = new ChannelConfiguration(); final String testChannel = "channelFromResolver"; resolvedChannel.setResolver(new TestChannelResolver(testChannel)); channelManager.addChannel(testChannel, resolvedChannel); final String channelParamValue = "channelFromParam"; MgnlContext.setAttribute(MultiChannelFilter.ENFORCE_CHANNEL_PARAMETER, channelParamValue); when(request.getRequestURL()).thenReturn(new StringBuffer("http: filter.doFilter(request, response, chain); assertEquals(channelParamValue, MgnlContext.getAggregationState().getChannel().getName()); } |
InterceptFilter extends AbstractMgnlFilter { public void intercept(HttpServletRequest request, HttpServletResponse response) throws LoginException, RepositoryException { final AggregationState aggregationState = MgnlContext.getAggregationState(); String action = request.getParameter(INTERCEPT); String repository = request.getParameter(PARAM_REPOSITORY); String nodePath = request.getParameter(PARAM_PATH); String handle = aggregationState.getHandle(); String channel = aggregationState.getChannel().getName(); if (repository == null) { repository = aggregationState.getRepository(); } if (repository == null) { repository = RepositoryConstants.WEBSITE; } final Session session = MgnlContext.getJCRSession(repository); if (ACTION_PREVIEW.equals(action)) { String preview = request.getParameter(MGNL_PREVIEW_ATTRIBUTE); log.debug("preview request parameter value is {} ", preview); if (preview != null) { if (Boolean.parseBoolean(preview)) { MgnlContext.setAttribute(MGNL_PREVIEW_ATTRIBUTE, Boolean.TRUE, Context.SESSION_SCOPE); MgnlContext.setAttribute(MultiChannelFilter.ENFORCE_CHANNEL_PARAMETER, channel, Context.SESSION_SCOPE); } else { MgnlContext.removeAttribute(MGNL_PREVIEW_ATTRIBUTE, Context.SESSION_SCOPE); MgnlContext.removeAttribute(MultiChannelFilter.ENFORCE_CHANNEL_PARAMETER, Context.SESSION_SCOPE); } } else { MgnlContext.removeAttribute(MGNL_PREVIEW_ATTRIBUTE, Context.SESSION_SCOPE); MgnlContext.removeAttribute(MultiChannelFilter.ENFORCE_CHANNEL_PARAMETER, Context.SESSION_SCOPE); } } else if (ACTION_NODE_DELETE.equals(action)) { try { Node page = session.getNode(handle); session.removeItem(nodePath); MetaDataUtil.updateMetaData(page); session.save(); } catch (RepositoryException e) { log.error("Exception caught: {}", e.getMessage(), e); } } else if (ACTION_NODE_SORT.equals(action)) { try { String pathSelected = request.getParameter(PARAM_PATH_SELECTED); String pathTarget = request.getParameter(PARAM_PATH_TARGET); String pathParent = StringUtils.substringBeforeLast(pathSelected, "/"); String srcName = StringUtils.substringAfterLast(pathSelected, "/"); String destName = StringUtils.substringAfterLast(pathTarget, "/"); String order = StringUtils.defaultIfEmpty(request.getParameter("order"), "before"); if (StringUtils.equalsIgnoreCase(destName, "mgnlNew")) { destName = null; } Node parent = session.getNode(pathParent + srcName); if ("before".equals(order)) { NodeUtil.orderBefore(parent, destName); } else { NodeUtil.orderAfter(parent, destName); } Node page = session.getNode(handle); MetaDataUtil.updateMetaData(page); session.save(); } catch (RepositoryException e) { log.error("Exception caught: {}", e.getMessage(), e); } } else { log.warn("Unknown action {}", action); } } @Override void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain); void intercept(HttpServletRequest request, HttpServletResponse response); static final String INTERCEPT; static final String PARAM_REPOSITORY; static final String PARAM_PATH; static final String MGNL_PREVIEW_ATTRIBUTE; } | @Test public void testPreviewIsSetInMgnlContextSession() throws Exception { when(request.getParameter(InterceptFilter.INTERCEPT)).thenReturn("PREVIEW"); when(request.getParameter(MGNL_PREVIEW)).thenReturn("true"); when(request.getParameter(MultiChannelFilter.ENFORCE_CHANNEL_PARAMETER)).thenReturn("desktop"); InterceptFilter filter = new InterceptFilter(); filter.intercept(request, response); assertNotNull(MgnlContext.getAttribute(MGNL_PREVIEW, Context.SESSION_SCOPE)); assertNotNull(MgnlContext.getAttribute(MultiChannelFilter.ENFORCE_CHANNEL_PARAMETER, Context.SESSION_SCOPE)); }
@Test public void testPreviewIsRemovedFromMgnlContextSession() throws Exception { when(request.getParameter(InterceptFilter.INTERCEPT)).thenReturn("PREVIEW"); when(request.getParameter(MGNL_PREVIEW)).thenReturn("false"); ctx.setAttribute(MGNL_PREVIEW, "true", Context.SESSION_SCOPE); when(request.getParameter(MultiChannelFilter.ENFORCE_CHANNEL_PARAMETER)).thenReturn("foo"); InterceptFilter filter = new InterceptFilter(); filter.intercept(request, response); assertNull(MgnlContext.getAttribute(MGNL_PREVIEW, Context.SESSION_SCOPE)); ctx.setAttribute(MGNL_PREVIEW, "true", Context.SESSION_SCOPE); when(request.getParameter(MGNL_PREVIEW)).thenReturn(null); when(request.getParameter(MultiChannelFilter.ENFORCE_CHANNEL_PARAMETER)).thenReturn(null); filter.intercept(request, response); assertNull(MgnlContext.getAttribute(MGNL_PREVIEW, Context.SESSION_SCOPE)); }
@Test(expected=PathNotFoundException.class) public void testDeleteNodeAction() throws Exception { when(request.getParameter(InterceptFilter.INTERCEPT)).thenReturn("NODE_DELETE"); when(request.getParameter("mgnlPath")).thenReturn("/1"); InterceptFilter filter = new InterceptFilter(); filter.intercept(request, response); ctx.getJCRSession("website").getNode("/1"); }
@Test public void testSortNodeDefaultAction() throws Exception { when(request.getParameter(InterceptFilter.INTERCEPT)).thenReturn("NODE_SORT"); when(request.getParameter("mgnlPathSelected")).thenReturn("/2"); when(request.getParameter("mgnlPathTarget")).thenReturn("/1"); when(request.getParameter("mgnlPath")).thenReturn("/"); when(request.getParameter("order")).thenReturn(null); NodeIterator nodes = ctx.getJCRSession("website").getRootNode().getNodes(); assertEquals("1", ((Node)nodes.next()).getName()); assertEquals("2", ((Node)nodes.next()).getName()); InterceptFilter filter = new InterceptFilter(); filter.intercept(request, response); nodes = ctx.getJCRSession("website").getRootNode().getNodes(); assertEquals("2", ((Node)nodes.next()).getName()); assertEquals("1", ((Node)nodes.next()).getName()); }
@Test public void testSortNodeBeforeAction() throws Exception { when(request.getParameter(InterceptFilter.INTERCEPT)).thenReturn("NODE_SORT"); when(request.getParameter("mgnlPathSelected")).thenReturn("/2"); when(request.getParameter("mgnlPathTarget")).thenReturn("/1"); when(request.getParameter("mgnlPath")).thenReturn("/"); when(request.getParameter("order")).thenReturn("before"); NodeIterator nodes = ctx.getJCRSession("website").getRootNode().getNodes(); assertEquals("1", ((Node)nodes.next()).getName()); assertEquals("2", ((Node)nodes.next()).getName()); InterceptFilter filter = new InterceptFilter(); filter.intercept(request, response); nodes = ctx.getJCRSession("website").getRootNode().getNodes(); assertEquals("2", ((Node)nodes.next()).getName()); assertEquals("1", ((Node)nodes.next()).getName()); }
@Test public void testSortNodeAfterAction() throws Exception { when(request.getParameter(InterceptFilter.INTERCEPT)).thenReturn("NODE_SORT"); when(request.getParameter("mgnlPathSelected")).thenReturn("/2"); when(request.getParameter("mgnlPathTarget")).thenReturn("/3"); when(request.getParameter("mgnlPath")).thenReturn("/"); when(request.getParameter("order")).thenReturn("after"); NodeIterator nodes = ctx.getJCRSession("website").getRootNode().getNodes(); assertEquals("1", ((Node)nodes.next()).getName()); assertEquals("2", ((Node)nodes.next()).getName()); assertEquals("3", ((Node)nodes.next()).getName()); InterceptFilter filter = new InterceptFilter(); filter.intercept(request, response); nodes = ctx.getJCRSession("website").getRootNode().getNodes(); assertEquals("1", ((Node)nodes.next()).getName()); assertEquals("3", ((Node)nodes.next()).getName()); assertEquals("2", ((Node)nodes.next()).getName()); } |
RangeSupportFilter extends AbstractMgnlFilter { @Override public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { isRangedRequest = request.getHeader("Range") != null; if (isRangedRequest) { response = wrapResponse(request, response); isServeContent = !"HEAD".equalsIgnoreCase(request.getMethod()); } chain.doFilter(request, response); } @Override void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain); boolean isWrapWriter(); void setWrapWriter(boolean wrapWriter); } | @Test public void testContentIsServedFromOutputStreamInNewRequestAfterHeadRequestWasExecuted() throws IOException, ServletException { final HttpServletRequest request = mock(HttpServletRequest.class); final HttpServletResponse response = mock(HttpServletResponse.class); final DummyFilter dummy = new DummyFilter(); final FilterChain chain = new FilterChain() { @Override public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { dummy.doFilter(request, response, this); } }; final DummyOutputStream output = new DummyOutputStream(); when(response.getOutputStream()).thenReturn(output); when(request.getHeader("Range")).thenReturn("bytes=0-56000"); when(request.getMethod()).thenReturn("HEAD").thenReturn("GET"); when(request.getDateHeader("If-Modified-Since")).thenReturn(-1L); final RangeSupportFilter filter = new RangeSupportFilter(); filter.doFilter(request, response, chain); ServletOutputStream out = dummy.getResponse().getOutputStream(); out.write("hi there".getBytes()); out.flush(); assertEquals("", output.toString()); filter.doFilter(request, response, chain); out = dummy.getResponse().getOutputStream(); out.write("hi there".getBytes()); out.flush(); assertEquals("hi there", output.toString()); }
@Test public void testContentLengthIsNotSet() throws IOException, ServletException { final HttpServletRequest request = mock(HttpServletRequest.class); final HttpServletResponse response = mock(HttpServletResponse.class); final DummyFilter dummy = new DummyFilter(); final FilterChain chain = new FilterChain() { @Override public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { dummy.doFilter(request, response, this); } }; final DummyOutputStream output = new DummyOutputStream(); when(response.getOutputStream()).thenReturn(output); when(request.getHeader("Range")).thenReturn("bytes=0-56000"); when(request.getMethod()).thenReturn("GET"); when(request.getDateHeader("If-Modified-Since")).thenReturn(-1L); final RangeSupportFilter filter = new RangeSupportFilter(); filter.doFilter(request, response, chain); dummy.getResponse().getOutputStream(); verify(response, times(0)).setContentLength(anyInt()); } |
WorkspaceMapping { public Repository getRepository(String repositoryId) { Repository repository = repositories.get(repositoryId); if (repository == null) { final String s = "Failed to retrieve repository '" + repositoryId + "'. Your Magnolia instance might not have been initialized properly."; log.warn(s); throw new IllegalArgumentException(s); } return repository; } void clearRepositories(); void clearAll(); void addRepositoryDefinition(RepositoryDefinition repositoryDefinition); void addWorkspaceMapping(WorkspaceMappingDefinition mapping); void addWorkspaceMappingDefinition(WorkspaceMappingDefinition definition); RepositoryDefinition getRepositoryDefinition(String repositoryId); Collection<String> getLogicalWorkspaceNames(); WorkspaceMappingDefinition getWorkspaceMapping(String logicalWorkspaceName); Collection<WorkspaceMappingDefinition> getWorkspaceMappings(); void setRepository(String repositoryId, Repository repository); void setRepositoryProvider(String repositoryId, Provider provider); Repository getRepository(String repositoryId); Provider getRepositoryProvider(String repositoryId); Collection<RepositoryDefinition> getRepositoryDefinitions(); } | @Test @Ignore public void testUnknownRepositoryShouldYieldMeaningfulExceptionMessage() { WorkspaceMapping mapping = new WorkspaceMapping(); try { mapping.getRepository("dummy"); fail("should have failed, since we haven't set any repository at all"); } catch (Throwable t) { assertEquals("Failed to retrieve repository 'dummy' (mapped as 'dummy'). Your Magnolia instance might not have been initialized properly.", t.getMessage()); } } |
RepositoryMappingDefinitionReader { public RepositoryMappingDefinition read(InputStream stream) throws JDOMException, IOException { SAXBuilder builder = new SAXBuilder(); Document document = builder.build(stream); Element root = document.getRootElement(); RepositoryMappingDefinition definition = new RepositoryMappingDefinition(); parseRepositoryMapping(root, definition); parseRepositories(root, definition); return definition; } RepositoryMappingDefinition read(InputStream stream); } | @Test public void testParse() throws Exception { InputStream stream = getClass().getResourceAsStream("test-repositories.xml"); RepositoryMappingDefinition definition = new RepositoryMappingDefinitionReader().read(stream); assertNotNull(definition); Collection<WorkspaceMappingDefinition> mappings = definition.getWorkspaceMappings(); assertEquals(3, mappings.size()); Iterator<WorkspaceMappingDefinition> iterator = mappings.iterator(); WorkspaceMappingDefinition mapping1 = iterator.next(); assertEquals("website", mapping1.getLogicalWorkspaceName()); assertEquals("magnolia", mapping1.getRepositoryName()); assertEquals("website", mapping1.getPhysicalWorkspaceName()); WorkspaceMappingDefinition mapping2 = iterator.next(); assertEquals("data", mapping2.getLogicalWorkspaceName()); assertEquals("anotherRepository", mapping2.getRepositoryName()); assertEquals("physicalName", mapping2.getPhysicalWorkspaceName()); WorkspaceMappingDefinition mapping3 = iterator.next(); assertEquals("config", mapping3.getLogicalWorkspaceName()); assertEquals("magnolia", mapping3.getRepositoryName()); assertEquals("config", mapping3.getPhysicalWorkspaceName()); Collection<RepositoryDefinition> repositories = definition.getRepositories(); assertEquals(3, repositories.size()); Iterator<RepositoryDefinition> repositoryDefinitionIterator = repositories.iterator(); RepositoryDefinition magnolia = repositoryDefinitionIterator.next(); assertEquals("magnolia", magnolia.getName()); assertEquals("provider-class", magnolia.getProvider()); assertTrue(magnolia.isLoadOnStartup()); assertEquals(2, magnolia.getParameters().size()); assertEquals("value1", magnolia.getParameters().get("parameter1")); assertEquals("value2", magnolia.getParameters().get("parameter2")); assertEquals(2, magnolia.getWorkspaces().size()); assertTrue(magnolia.getWorkspaces().contains("website")); assertTrue(magnolia.getWorkspaces().contains("config")); RepositoryDefinition anotherRepository = repositoryDefinitionIterator.next(); assertEquals("anotherRepository", anotherRepository.getName()); assertEquals("another-provider-class", anotherRepository.getProvider()); assertFalse(anotherRepository.isLoadOnStartup()); assertEquals(0, anotherRepository.getParameters().size()); assertEquals(1, anotherRepository.getWorkspaces().size()); assertTrue(anotherRepository.getWorkspaces().contains("physicalName")); RepositoryDefinition repositoryWithoutWorkspaces = repositoryDefinitionIterator.next(); assertEquals("repositoryWithoutWorkspaces", repositoryWithoutWorkspaces.getName()); assertEquals("third-provider-class", repositoryWithoutWorkspaces.getProvider()); assertFalse(repositoryWithoutWorkspaces.isLoadOnStartup()); assertEquals(0, repositoryWithoutWorkspaces.getParameters().size()); assertEquals(1, repositoryWithoutWorkspaces.getWorkspaces().size()); assertTrue(repositoryWithoutWorkspaces.getWorkspaces().contains("default")); } |
NodeBuilder { public void exec() throws NodeOperationException { for (NodeOperation childrenOp : childrenOps) { childrenOp.exec(root, errorHandler); } } NodeBuilder(Content root, NodeOperation... childrenOps); NodeBuilder(ErrorHandler errorHandler, Content root, NodeOperation... childrenOps); void exec(); } | @Test public void testContextNodeIsProperlyPropagated() throws Exception { final HierarchyManager hm = MgnlContext.getHierarchyManager("config"); { final Content hello = hm.getRoot().createContent("MyRoot").createContent("hello"); final Content w = hello.createContent("world"); w.createNodeData("foo", "bar"); hello.createContent("zing").createNodeData("this", "will be removed"); } final MessageTracker messageTracker = new MessageTracker(); final NodeBuilder nodeBuilder = new NodeBuilder(messageTracker, hm.getContent("MyRoot"), getNode("hello").then( addNode("newsub").then( addProperty("newProp", "New Value") ), remove("zing"), getNode("world").then( remove("foo") ) ), addNode("other").then(addProperty("X", "Y")), addProperty("lala", "lolo"), addProperty("oldName", "some String value"), renameProperty("oldName", "newName") ); nodeBuilder.exec(); hm.save(); final NodeData prop = hm.getNodeData("/MyRoot/hello/newsub/newProp"); assertTrue("Property should have been created", prop.isExist()); assertEquals("New Value", prop.getString()); assertEquals("Y", hm.getNodeData("/MyRoot/other/X").getString()); assertEquals("lolo", hm.getNodeData("/MyRoot/lala").getString()); assertFalse("Node should have been removed", hm.isExist("/MyRoot/hello/zing")); assertFalse("Property should have been removed", hm.isExist("/MyRoot/hello/world/foo")); assertEquals(0, messageTracker.getMessages().size()); assertFalse(hm.getContent("/MyRoot").hasNodeData("oldName")); assertNotNull(hm.getContent("/MyRoot").getNodeData("newName")); assertEquals("some String value", hm.getNodeData("/MyRoot/newName").getString()); }
@Test public void testErrorMessages() throws Exception { final HierarchyManager hm = MgnlContext.getHierarchyManager("config"); { final Content hello = hm.getRoot().createContent("MyRoot").createContent("hello"); final Content world = hello.createContent("world"); world.createNodeData("foo", "bar"); world.createNodeData("baz", "baz-current"); } final MessageTracker messageTracker = new MessageTracker(); final NodeBuilder nodeBuilder = new NodeBuilder(messageTracker, hm.getContent("MyRoot"), getNode("hello").then( setProperty("unexisting1", "won't be set"), setProperty("unexisting2", "does not exist and", "won't be set"), remove("unexisting3"), getNode("world").then( addProperty("baz", "baz"), setProperty("baz", "expected", "new"), getNode("subsub"), getNode("chalala/zeuzeu") ) )); nodeBuilder.exec(); hm.save(); assertEquals(7, messageTracker.getMessages().size()); assertEquals("unexisting1 can't be found at /MyRoot/hello.", messageTracker.getMessages().get(0)); assertEquals("unexisting2 can't be found at /MyRoot/hello.", messageTracker.getMessages().get(1)); assertEquals("unexisting3 can't be found at /MyRoot/hello.", messageTracker.getMessages().get(2)); assertEquals("baz already exists at /MyRoot/hello/world.", messageTracker.getMessages().get(3)); assertEquals("Expected expected at /MyRoot/hello/world/baz but found baz-current instead; can't set value to new.", messageTracker.getMessages().get(4)); assertEquals("subsub can't be found at /MyRoot/hello/world.", messageTracker.getMessages().get(5)); assertEquals("chalala/zeuzeu can't be found at /MyRoot/hello/world.", messageTracker.getMessages().get(6)); }
@Test public void testPropertyNotReplaceIfCurrentValueDoesNotMatchExpectations() throws Exception { final HierarchyManager hm = MgnlContext.getHierarchyManager("config"); { final Content hello = hm.getRoot().createContent("MyRoot").createContent("hello"); hello.createNodeData("foo", "foo-current"); hello.createNodeData("baz", "baz-current"); } final MessageTracker messageTracker = new MessageTracker(); final NodeBuilder nodeBuilder = new NodeBuilder(messageTracker, hm.getContent("MyRoot"), getNode("hello").then( setProperty("foo", "foo-current", "foo-replaced"), setProperty("baz", "baz-unexpected", "baz-not-replaced") )); nodeBuilder.exec(); hm.save(); assertEquals("foo-replaced", hm.getNodeData("/MyRoot/hello/foo").getString()); assertEquals(1, messageTracker.getMessages().size()); assertEquals("Expected baz-unexpected at /MyRoot/hello/baz but found baz-current instead; can't set value to baz-not-replaced.", messageTracker.getMessages().get(0)); assertEquals("baz-current", hm.getNodeData("/MyRoot/hello/baz").getString()); } |
Ops { public static NodeOperation addProperty(final String name, final Object value) { return new AbstractNodeOperation() { @Override protected Content doExec(Content context, ErrorHandler errorHandler) throws RepositoryException { if (context.hasNodeData(name)) { throw new ItemExistsException(name); } context.createNodeData(name, value); return context; } }; } static NodeOperation addNode(final String name); static NodeOperation addNode(final String name, final String type); static NodeOperation addNode(final String name, final ItemType type); static NodeOperation getNode(final String name); static NodeOperation remove(final String name); static NodeOperation addProperty(final String name, final Object value); static NodeOperation setProperty(final String name, final Object newValue); static NodeOperation setProperty(final String name, final Object expectedCurrentValue, final Object newValue); static NodeOperation renameNode(final String currentName, final String newName); static NodeOperation renameProperty(final String name, final String newName); static NodeOperation moveNode(final String nodeName, final String dest); static NodeOperation copyNode(final String nodeName, final String dest); static NodeOperation onChildNodes(final NodeOperation... childrenOps); static NodeOperation onChildNodes(final String type, final NodeOperation... childrenOps); static NodeOperation onChildNodes(final ItemType type, final NodeOperation... childrenOps); static NodeOperation onChildNodes(final Content.ContentFilter filter, final NodeOperation... childrenOps); static NodeOperation noop(); } | @Test public void testAddPropertyFailsIfPropertyExists() throws Exception { final HierarchyManager hm = MgnlContext.getHierarchyManager("config"); final Content node = hm.getRoot().createContent("hello"); node.createNodeData("foo", "bar"); hm.save(); try { final NodeOperation op = Ops.addProperty("foo", "zazoo"); op.exec(node, eh); fail("should have failed"); } catch (Throwable e) { assertEquals("foo", e.getMessage()); } } |
Ops { public static NodeOperation setProperty(final String name, final Object newValue) { return new AbstractNodeOperation() { @Override protected Content doExec(Content context, ErrorHandler errorHandler) throws RepositoryException { if (!context.hasNodeData(name)) { throw new ItemNotFoundException(name); } final Value value = NodeDataUtil.createValue(newValue, context.getJCRNode().getSession().getValueFactory()); context.setNodeData(name, value); return context; } }; } static NodeOperation addNode(final String name); static NodeOperation addNode(final String name, final String type); static NodeOperation addNode(final String name, final ItemType type); static NodeOperation getNode(final String name); static NodeOperation remove(final String name); static NodeOperation addProperty(final String name, final Object value); static NodeOperation setProperty(final String name, final Object newValue); static NodeOperation setProperty(final String name, final Object expectedCurrentValue, final Object newValue); static NodeOperation renameNode(final String currentName, final String newName); static NodeOperation renameProperty(final String name, final String newName); static NodeOperation moveNode(final String nodeName, final String dest); static NodeOperation copyNode(final String nodeName, final String dest); static NodeOperation onChildNodes(final NodeOperation... childrenOps); static NodeOperation onChildNodes(final String type, final NodeOperation... childrenOps); static NodeOperation onChildNodes(final ItemType type, final NodeOperation... childrenOps); static NodeOperation onChildNodes(final Content.ContentFilter filter, final NodeOperation... childrenOps); static NodeOperation noop(); } | @Test public void testSetPropertyFailsIfPropertyDoesNotExist() throws Exception { final HierarchyManager hm = MgnlContext.getHierarchyManager("config"); final Content node = hm.getRoot().createContent("hello"); node.createNodeData("foo", "bar"); hm.save(); try { final NodeOperation op = Ops.setProperty("foo", "baz", "zazoo"); op.exec(node, eh); fail("should have failed"); } catch (Throwable e) { assertEquals("Expected baz at /hello/foo but found bar instead; can't set value to zazoo.", e.getMessage()); } }
@Test public void testSetPropertyFailsIfPropertyDoesNotHaveExpectedValue() throws Exception { final HierarchyManager hm = MgnlContext.getHierarchyManager("config"); final Content node = hm.getRoot().createContent("hello"); hm.save(); try { final NodeOperation op = Ops.setProperty("foo", "zazoo"); op.exec(node, eh); fail("should have failed"); } catch (Throwable e) { assertEquals("foo", e.getMessage()); } } |
Ops { public static NodeOperation remove(final String name) { return new AbstractNodeOperation() { @Override protected Content doExec(Content context, ErrorHandler errorHandler) throws RepositoryException { context.delete(name); return context; } }; } static NodeOperation addNode(final String name); static NodeOperation addNode(final String name, final String type); static NodeOperation addNode(final String name, final ItemType type); static NodeOperation getNode(final String name); static NodeOperation remove(final String name); static NodeOperation addProperty(final String name, final Object value); static NodeOperation setProperty(final String name, final Object newValue); static NodeOperation setProperty(final String name, final Object expectedCurrentValue, final Object newValue); static NodeOperation renameNode(final String currentName, final String newName); static NodeOperation renameProperty(final String name, final String newName); static NodeOperation moveNode(final String nodeName, final String dest); static NodeOperation copyNode(final String nodeName, final String dest); static NodeOperation onChildNodes(final NodeOperation... childrenOps); static NodeOperation onChildNodes(final String type, final NodeOperation... childrenOps); static NodeOperation onChildNodes(final ItemType type, final NodeOperation... childrenOps); static NodeOperation onChildNodes(final Content.ContentFilter filter, final NodeOperation... childrenOps); static NodeOperation noop(); } | @Test public void testRemoveFailsOnUnexistingPropertyOrNode() throws Exception { final HierarchyManager hm = MgnlContext.getHierarchyManager("config"); hm.getRoot().createContent("hello").createNodeData("foo", "bar"); hm.save(); final Content root = hm.getContent("/hello"); try { final NodeOperation op = Ops.remove("non-existing"); op.exec(root, eh); fail("should have failed"); } catch (Throwable e) { assertEquals("non-existing", e.getMessage()); } } |
Ops { public static NodeOperation renameProperty(final String name, final String newName) { return new AbstractNodeOperation() { @Override protected Content doExec(Content context, ErrorHandler errorHandler) throws RepositoryException { if (!context.hasNodeData(name)) { throw new ItemNotFoundException(name); } if (context.hasNodeData(newName)) { throw new ItemExistsException(newName); } final Value value = context.getNodeData(name).getValue(); context.setNodeData(newName, value); context.deleteNodeData(name); return context; } }; } static NodeOperation addNode(final String name); static NodeOperation addNode(final String name, final String type); static NodeOperation addNode(final String name, final ItemType type); static NodeOperation getNode(final String name); static NodeOperation remove(final String name); static NodeOperation addProperty(final String name, final Object value); static NodeOperation setProperty(final String name, final Object newValue); static NodeOperation setProperty(final String name, final Object expectedCurrentValue, final Object newValue); static NodeOperation renameNode(final String currentName, final String newName); static NodeOperation renameProperty(final String name, final String newName); static NodeOperation moveNode(final String nodeName, final String dest); static NodeOperation copyNode(final String nodeName, final String dest); static NodeOperation onChildNodes(final NodeOperation... childrenOps); static NodeOperation onChildNodes(final String type, final NodeOperation... childrenOps); static NodeOperation onChildNodes(final ItemType type, final NodeOperation... childrenOps); static NodeOperation onChildNodes(final Content.ContentFilter filter, final NodeOperation... childrenOps); static NodeOperation noop(); } | @Test public void testRenamePropertyAndCheckValueForString() throws Exception { final HierarchyManager hm = MgnlContext.getHierarchyManager("config"); hm.getRoot().createContent("hello").setNodeData("fooOld", "bar"); hm.save(); final Content root = hm.getContent("/hello"); final NodeOperation op = Ops.renameProperty("fooOld", "fooNew"); op.exec(root, eh); assertFalse(root.hasNodeData("fooOld")); assertNotNull(root.getNodeData("fooNew")); assertEquals("bar", root.getNodeData("fooNew").getString()); } |
ContentOps { public static NodeOperation createContent(String name, ItemType type) { return Ops.addNode(name, type); } static NodeOperation createContent(String name, ItemType type); static NodeOperation createPage(String name, String template); static NodeOperation createCollectionNode(String name); static NodeOperation createParagraph(String name, String template); static NodeOperation setNodeData(final String name, final Object value); static NodeOperation setBinaryNodeData(final String name, final String fileName, final long size, final InputStream inputStream); static NodeOperation setTemplate(final String template); } | @Test public void testCreateContent() throws RepositoryException { MockContent root = new MockContent(ROOT_NAME); ContentOps.createContent(NEW_CONTENT_NAME, ItemType.CONTENTNODE).exec(root, ERROR_HANDLER); assertTrue(root.hasContent(NEW_CONTENT_NAME)); assertEquals(ItemType.CONTENTNODE, root.getContent(NEW_CONTENT_NAME).getItemType()); } |
ContentOps { public static NodeOperation createCollectionNode(String name) { return createContent(name, ItemType.CONTENTNODE); } static NodeOperation createContent(String name, ItemType type); static NodeOperation createPage(String name, String template); static NodeOperation createCollectionNode(String name); static NodeOperation createParagraph(String name, String template); static NodeOperation setNodeData(final String name, final Object value); static NodeOperation setBinaryNodeData(final String name, final String fileName, final long size, final InputStream inputStream); static NodeOperation setTemplate(final String template); } | @Test public void testCreateCollectionNode() throws RepositoryException { MockContent root = new MockContent(ROOT_NAME); ContentOps.createCollectionNode(NEW_CONTENT_NAME).exec(root, ERROR_HANDLER); assertTrue(root.hasContent(NEW_CONTENT_NAME)); assertEquals(ItemType.CONTENTNODE, root.getContent(NEW_CONTENT_NAME).getItemType()); } |
ContentOps { public static NodeOperation setNodeData(final String name, final Object value) { return new AbstractNodeOperation() { @Override protected Content doExec(Content context, ErrorHandler errorHandler) throws RepositoryException { context.setNodeData(name, value); return context; } }; } static NodeOperation createContent(String name, ItemType type); static NodeOperation createPage(String name, String template); static NodeOperation createCollectionNode(String name); static NodeOperation createParagraph(String name, String template); static NodeOperation setNodeData(final String name, final Object value); static NodeOperation setBinaryNodeData(final String name, final String fileName, final long size, final InputStream inputStream); static NodeOperation setTemplate(final String template); } | @Test public void testSetNodeData() { MockContent content = new MockContent(NEW_CONTENT_NAME); ContentOps.setNodeData(NODEDATA_NAME, NODEDATA_VALUE).exec(content, ERROR_HANDLER); assertEquals(NODEDATA_VALUE, content.getNodeData(NODEDATA_NAME).getString()); } |
ContentOps { public static NodeOperation setBinaryNodeData(final String name, final String fileName, final long size, final InputStream inputStream) { return new AbstractNodeOperation() { @Override protected Content doExec(Content context, ErrorHandler errorHandler) throws RepositoryException { NodeData binary = context.setNodeData(name, inputStream); binary.setAttribute(FileProperties.PROPERTY_FILENAME, StringUtils.substringBeforeLast(fileName, ".")); binary.setAttribute(FileProperties.PROPERTY_EXTENSION, StringUtils.substringAfterLast(fileName, ".")); binary.setAttribute(FileProperties.PROPERTY_SIZE, Long.toString(size)); return context; } }; } static NodeOperation createContent(String name, ItemType type); static NodeOperation createPage(String name, String template); static NodeOperation createCollectionNode(String name); static NodeOperation createParagraph(String name, String template); static NodeOperation setNodeData(final String name, final Object value); static NodeOperation setBinaryNodeData(final String name, final String fileName, final long size, final InputStream inputStream); static NodeOperation setTemplate(final String template); } | @Test public void testSetBinaryNodeData() throws IOException { MockContent content = new MockContent(NEW_CONTENT_NAME); byte[] bytes = {'C', 'O', 'N', 'T', 'E', 'N', 'T'}; ContentOps.setBinaryNodeData(NODEDATA_NAME, "test.jpg", bytes.length, new ByteArrayInputStream(bytes)).exec(content, ERROR_HANDLER); NodeData nodeData = content.getNodeData(NODEDATA_NAME); assertEquals("test", nodeData.getAttribute(FileProperties.PROPERTY_FILENAME)); assertEquals("jpg", nodeData.getAttribute(FileProperties.PROPERTY_EXTENSION)); assertEquals(String.valueOf(bytes.length), nodeData.getAttribute(FileProperties.PROPERTY_SIZE)); InputStream stream = nodeData.getStream(); assertEquals(new String(bytes), IOUtils.toString(stream)); } |
SimpleContext extends AbstractMapBasedContext { @Override public Session getJCRSession(String workspaceName) throws LoginException, RepositoryException { return this.ctx.getJCRSession(workspaceName); } SimpleContext(); SimpleContext(Map<String, Object> map); @Override AccessManager getAccessManager(String workspaceId); @Override HierarchyManager getHierarchyManager(String workspaceId); @Override Session getJCRSession(String workspaceName); @Override User getUser(); @Override QueryManager getQueryManager(String workspaceId); @Override void release(); } | @Test public void testSimpleContextDelegateGetJCRSessionMethod() throws Exception { ComponentsTestUtil.setInstance(SystemContext.class, new JCRSessionPerThreadSystemContext()); MgnlContext.setInstance(new SimpleContext(Components.getComponent(SystemContext.class))); assertNotNull(MgnlContext.getJCRSession("website")); } |
DefaultRepositoryStrategy extends AbstractRepositoryStrategy { protected Credentials getCredentials() { User user = MgnlContext.getUser(); if (user == null) { String user1 = SystemProperty.getProperty("magnolia.connection.jcr.anonymous.userId", "anonymous"); String pwd = SystemProperty.getProperty("magnolia.connection.jcr.anonymous.password", "anonymous"); return new SimpleCredentials(user1, pwd.toCharArray()); } final String password = user.getPassword(); if (password == null) { return new SimpleCredentials(user.getName(), "".toCharArray()); } else { return new SimpleCredentials(user.getName(), password.toCharArray()); } } @Inject DefaultRepositoryStrategy(RepositoryManager repositoryManager, UserContext context); @Override void release(); } | @Test public void testGetUserCredentialsReturnsCredentialsFromContextUserIfSet() { Context context = mock(Context.class); MgnlContext.setInstance(context); User user = mock(User.class); when(context.getUser()).thenReturn(user); when(user.getName()).thenReturn("user"); when(user.getPassword()).thenReturn("password"); SimpleCredentials credentials = (SimpleCredentials) strategy.getCredentials(); assertEquals("user", credentials.getUserID()); assertEquals("password", new String(credentials.getPassword())); }
@Test public void testPasswordIsNull() { Context context = mock(Context.class); MgnlContext.setInstance(context); User user = mock(User.class); when(context.getUser()).thenReturn(user); when(user.getName()).thenReturn("user"); when(user.getPassword()).thenReturn(null); SimpleCredentials credentials = (SimpleCredentials) strategy.getCredentials(); assertEquals("user", credentials.getUserID()); assertEquals("", new String(credentials.getPassword())); } |
MgnlContext { @Deprecated public static void doInSystemContext(final SystemContextOperation op) { doInSystemContext(op, false); } MgnlContext(); static User getUser(); static void setLocale(Locale locale); static Locale getLocale(); static Messages getMessages(); static Messages getMessages(String basename); static void login(Subject subject); @Deprecated static HierarchyManager getHierarchyManager(String repositoryId); static AccessManager getAccessManager(String name); @Deprecated static QueryManager getQueryManager(String workspaceName); static MultipartForm getPostedForm(); static String getParameter(String name); static String[] getParameterValues(String name); static Map<String, String> getParameters(); static String getContextPath(); static AggregationState getAggregationState(); static void resetAggregationState(); static void setAttribute(String name, Object value); static void setAttribute(String name, Object value, int scope); static T getAttribute(String name); static T getAttribute(String name, int scope); static boolean hasAttribute(String name); static boolean hasAttribute(String name, int scope); static void removeAttribute(String name); static void removeAttribute(String name, int scope); static void setInstance(Context context); static Context getInstance(); static WebContext getWebContext(); static WebContext getWebContext(String exceptionMessage); static WebContext getWebContextOrNull(); static boolean hasInstance(); static boolean isSystemInstance(); static boolean isWebContext(); @Deprecated static SystemContext getSystemContext(); @Deprecated static void doInSystemContext(final SystemContextOperation op); static T doInSystemContext(final Op<T, E> op); @Deprecated static void doInSystemContext(final SystemContextOperation op, boolean releaseAfterExecution); static T doInSystemContext(final Op<T, E> op, boolean releaseAfterExecution); @Deprecated static void initAsWebContext(HttpServletRequest request, HttpServletResponse response, ServletContext servletContext); static void release(); static void push(HttpServletRequest request, HttpServletResponse response); static void pop(); static Session getJCRSession(String workspaceName); static Subject getSubject(); } | @Test public void testCanDeclareCheckExceptionToBeThrownByDoInSystemContext() { final RepositoryException testEx = new RepositoryException("test!"); try { MgnlContext.doInSystemContext(new MgnlContext.Op<Content, RepositoryException>() { @Override public Content exec() throws RepositoryException { throw testEx; } }); fail("should have thrown an exception !"); } catch (Throwable e) { assertSame(testEx, e); } }
@Test public void testCanThrowRuntimeExceptionsWithoutSpecificThrowsClauseInDoInSystemContext() { final IllegalStateException testEx = new IllegalStateException("test!"); try { MgnlContext.doInSystemContext(new MgnlContext.Op<Object, RuntimeException>() { @Override public Object exec() { throw testEx; } }); fail("should have thrown an exception !"); } catch (Throwable e) { assertSame(testEx, e); } } |
AbstractRepositoryStrategy implements JCRSessionStrategy { @Override public Session getSession(String workspaceName) throws LoginException, RepositoryException { Session jcrSession = jcrSessions.get(workspaceName); if (jcrSession == null) { log.debug("creating jcr session {} by thread {}", workspaceName, Thread.currentThread().getName()); jcrSession = internalGetSession(workspaceName); jcrSessions.put(workspaceName, jcrSession); } return jcrSession; } @Inject protected AbstractRepositoryStrategy(RepositoryManager repositoryManager); @Override Session getSession(String workspaceName); } | @Test public void testGetSession() throws Exception { Session session = strategy.getSession("website"); assertNotNull(session); strategy.release(); } |
MetaDataImportPostProcessor implements ImportPostProcessor { @Override public void postProcessNode(Node node) throws RepositoryException { MetaDataAsMixinConversionHelper conversionHelper = new MetaDataAsMixinConversionHelper(); conversionHelper.setDeleteMetaDataIfEmptied(true); conversionHelper.setPeriodicSaves(false); conversionHelper.convertNodeAndChildren(node); } @Override void postProcessNode(Node node); } | @Test public void testMetaDataPropertiesAreConverted() throws RepositoryException { Session session = MgnlContext.getJCRSession("config"); Node node = session.getRootNode().addNode("test"); Node md = node.addNode("MetaData", NodeTypes.MetaData.NAME); Calendar calendar = Calendar.getInstance(); md.setProperty("mgnl:creationdate", calendar); md.setProperty("mgnl:lastaction", calendar); md.setProperty("mgnl:activatorid", "superuser"); md.setProperty("mgnl:activated", "2"); md.setProperty("mgnl:template", "samples:pages/some/page"); md.setProperty("mgnl:authorid", "hyperuser"); md.setProperty("mgnl:lastmodified", calendar); node.setProperty("mgnl:deletedOn", calendar); new MetaDataImportPostProcessor().postProcessNode(node); assertPropertyEquals(node, NodeTypes.Created.CREATED, calendar); assertPropertyEquals(node, NodeTypes.Activatable.LAST_ACTIVATED, calendar); assertPropertyEquals(node, NodeTypes.Activatable.LAST_ACTIVATED_BY, "superuser"); assertPropertyEquals(node, NodeTypes.Activatable.ACTIVATION_STATUS, "2"); assertPropertyEquals(node, NodeTypes.Renderable.TEMPLATE, "samples:pages/some/page"); assertPropertyEquals(node, NodeTypes.LastModified.LAST_MODIFIED_BY, "hyperuser"); assertPropertyEquals(node, NodeTypes.LastModified.LAST_MODIFIED, calendar); assertPropertyEquals(node, NodeTypes.Deleted.DELETED, calendar); } |
PropertiesImportExport { protected Object convertNodeDataStringToObject(String valueStr) { if (contains(valueStr, ':')) { final String type = StringUtils.substringBefore(valueStr, ":"); final String value = StringUtils.substringAfter(valueStr, ":"); if (type.equalsIgnoreCase("date")) { return ISO8601.parse(value); } else if (type.equalsIgnoreCase("binary")) { return new ByteArrayInputStream(value.getBytes()); } else { try { final Class<?> typeCl; if (type.equals("int")) { typeCl = Integer.class; } else { typeCl = Class.forName("java.lang." + StringUtils.capitalize(type)); } return ConvertUtils.convert(value, typeCl); } catch (ClassNotFoundException e) { return valueStr; } } } return valueStr; } void createContent(Content root, InputStream propertiesStream); @Deprecated static Properties toProperties(HierarchyManager hm); static Properties toProperties(Content rootContent); static Properties contentToProperties(HierarchyManager hm); static Properties contentToProperties(Content rootContent); static Properties contentToProperties(Content rootContent, Content.ContentFilter filter); static void appendNodeProperties(Content node, Properties out); static String dumpPropertiesToString(Content content, Content.ContentFilter filter); static String dumpPropertiesToString(Properties properties); } | @Test public void testConvertsToStringByDefault() throws IOException, RepositoryException { final PropertiesImportExport pie = new PropertiesImportExport(); assertEquals("foo", pie.convertNodeDataStringToObject("foo")); assertEquals("bar", pie.convertNodeDataStringToObject("string:bar")); assertEquals("2009-10-14T08:59:01.227-04:00", pie.convertNodeDataStringToObject("string:2009-10-14T08:59:01.227-04:00")); }
@Test public void testConvertsToWrapperType() { final PropertiesImportExport pie = new PropertiesImportExport(); assertEquals(Boolean.TRUE, pie.convertNodeDataStringToObject("boolean:true")); assertEquals(Boolean.FALSE, pie.convertNodeDataStringToObject("boolean:false")); assertEquals(Integer.valueOf(5), pie.convertNodeDataStringToObject("integer:5")); final Object dateConvertedObject = pie.convertNodeDataStringToObject("date:2009-10-14T08:59:01.227-04:00"); assertTrue(dateConvertedObject instanceof Calendar); assertEquals(1255525141227L, ((Calendar) dateConvertedObject).getTimeInMillis()); final Object dateOnlyObject = pie.convertNodeDataStringToObject("date:2009-12-12"); assertNull(dateOnlyObject); }
@Test public void testCanUseIntShortcutForConvertingIntegers() { final PropertiesImportExport pie = new PropertiesImportExport(); assertEquals(Integer.valueOf(37), pie.convertNodeDataStringToObject("int:37")); } |
BootstrapUtil { public static String getWorkspaceNameFromResource(final String resourcePath) { String resourceName = StringUtils.replace(resourcePath, "\\", "/"); String name = getFilenameFromResource(resourceName, ".xml"); String fullPath = DataTransporter.revertExportPath(name); return StringUtils.substringBefore(fullPath, "/"); } static void bootstrap(String[] resourceNames, int importUUIDBehavior); static void export(Content content, File directory); static String getWorkspaceNameFromResource(final String resourcePath); static String getFullpathFromResource(final String resourcePath); static String getPathnameFromResource(final String resourcePath); static String getFilenameFromResource(final String resourcePath, final String extension); } | @Test public void testGetWorkspaceNameFromResource() throws Exception { String workspace = BootstrapUtil.getWorkspaceNameFromResource(MGNL_BOOTSTRAP_FILE); assertEquals("config", workspace); workspace = BootstrapUtil.getWorkspaceNameFromResource(MGNL_BOOTSTRAP_FILE_NEW_STYLE); assertEquals("config", workspace); } |
BootstrapUtil { public static String getPathnameFromResource(final String resourcePath) { String resourceName = StringUtils.replace(resourcePath, "\\", "/"); String name = getFilenameFromResource(resourceName, ".xml"); String fullPath = DataTransporter.revertExportPath(name); String pathName = StringUtils.substringAfter(StringUtils.substringBeforeLast(fullPath, "/"), "/"); if(!pathName.startsWith("/")) { pathName = "/" + pathName; } return pathName; } static void bootstrap(String[] resourceNames, int importUUIDBehavior); static void export(Content content, File directory); static String getWorkspaceNameFromResource(final String resourcePath); static String getFullpathFromResource(final String resourcePath); static String getPathnameFromResource(final String resourcePath); static String getFilenameFromResource(final String resourcePath, final String extension); } | @Test public void testGetPathnameFromResource() throws Exception { String pathname = BootstrapUtil.getPathnameFromResource(MGNL_BOOTSTRAP_FILE); assertEquals("/server", pathname); pathname = BootstrapUtil.getPathnameFromResource(MGNL_BOOTSTRAP_FILE_NEW_STYLE); assertEquals("/server", pathname); pathname = BootstrapUtil.getPathnameFromResource(MGNL_BOOTSTRAP_FILE_NEW_STYLE_NO_SLASHES); assertEquals("/server", pathname); } |
BootstrapUtil { public static String getFullpathFromResource(final String resourcePath) { String resourceName = StringUtils.replace(resourcePath, "\\", "/"); String name = getFilenameFromResource(resourceName, ".xml"); String fullPath = DataTransporter.revertExportPath(name); String repository = StringUtils.substringBefore(fullPath, "/"); return StringUtils.removeStart(fullPath, repository); } static void bootstrap(String[] resourceNames, int importUUIDBehavior); static void export(Content content, File directory); static String getWorkspaceNameFromResource(final String resourcePath); static String getFullpathFromResource(final String resourcePath); static String getPathnameFromResource(final String resourcePath); static String getFilenameFromResource(final String resourcePath, final String extension); } | @Test public void testGetFullpathFromResource() throws Exception { String fullpath = BootstrapUtil.getFullpathFromResource(MGNL_BOOTSTRAP_FILE); assertEquals("/server/i18n", fullpath); fullpath = BootstrapUtil.getFullpathFromResource(MGNL_BOOTSTRAP_FILE_NEW_STYLE); assertEquals("/server/foo.i18n", fullpath); fullpath = BootstrapUtil.getFullpathFromResource(MGNL_BOOTSTRAP_FILE_NEW_STYLE_NO_SLASHES); assertEquals("/server/foo.i18n", fullpath); } |
BootstrapUtil { public static String getFilenameFromResource(final String resourcePath, final String extension) { String ext = StringUtils.defaultIfEmpty(extension, ".xml"); String tmpResourcePath = resourcePath; if(resourcePath.contains("/")) { tmpResourcePath = StringUtils.substringAfterLast(resourcePath, "/"); } return StringUtils.removeEnd(tmpResourcePath, ext.startsWith(".") ? ext : "." + ext); } static void bootstrap(String[] resourceNames, int importUUIDBehavior); static void export(Content content, File directory); static String getWorkspaceNameFromResource(final String resourcePath); static String getFullpathFromResource(final String resourcePath); static String getPathnameFromResource(final String resourcePath); static String getFilenameFromResource(final String resourcePath, final String extension); } | @Test public void testGetFilenameFromResource() throws Exception { String fileName = BootstrapUtil.getFilenameFromResource(MGNL_BOOTSTRAP_FILE, null); assertEquals("config.server.i18n", fileName); fileName = BootstrapUtil.getFilenameFromResource(MGNL_BOOTSTRAP_FILE, "xml"); assertEquals("config.server.i18n", fileName); fileName = BootstrapUtil.getFilenameFromResource(MGNL_BOOTSTRAP_FILE_NEW_STYLE, null); assertEquals("config.server.foo..i18n", fileName); fileName = BootstrapUtil.getFilenameFromResource("/mgnl-bootstrap/foo/bar..baz.qux", ".qux"); assertEquals("bar..baz", fileName); fileName = BootstrapUtil.getFilenameFromResource(MGNL_BOOTSTRAP_FILE_NEW_STYLE_NO_SLASHES, ".xml"); assertEquals("config.server.foo..i18n", fileName); } |
DataTransporter { public static void parseAndFormat(OutputStream stream, XMLReader reader, String repository, String basepath, Session session, boolean noRecurse) throws IOException, SAXException, PathNotFoundException, RepositoryException { if (reader == null) { reader = XMLReaderFactory.createXMLReader(org.apache.xerces.parsers.SAXParser.class.getName()); } File tempFile = File.createTempFile("export-" + repository + session.getUserID(), ".xml"); OutputStream fileStream = new FileOutputStream(tempFile); try { session.exportSystemView(basepath, fileStream, false, noRecurse); } finally { IOUtils.closeQuietly(fileStream); } readFormatted(reader, tempFile, stream); if (!tempFile.delete()) { log.warn("Could not delete temporary export file {}", tempFile.getAbsolutePath()); } } static synchronized void importDocument(Document xmlDocument, String repositoryName, String basepath,
boolean keepVersionHistory, int importMode, boolean saveAfterImport,
boolean createBasepathIfNotExist); static synchronized void importFile(File xmlFile, String repositoryName, String basepath,
boolean keepVersionHistory, int importMode, boolean saveAfterImport,
boolean createBasepathIfNotExist); static void executeBootstrapImport(File xmlFile, String repositoryName); static void importProperties(Properties properties, String repositoryName); static synchronized void importXmlStream(InputStream xmlStream, String repositoryName, String basepath,
String name, boolean keepVersionHistory, int importMode,
boolean saveAfterImport, boolean createBasepathIfNotExist); static void executeExport(OutputStream baseOutputStream, boolean keepVersionHistory, boolean format,
Session session, String basepath, String repository, String ext); static void parseAndFormat(OutputStream stream, XMLReader reader, String repository, String basepath,
Session session, boolean noRecurse); static String encodePath(String path, String separator, String enc); static String decodePath(String path, String enc); static String createExportPath(String path); static String revertExportPath(String exportPath); static final String ZIP; static final String GZ; static final String XML; static final String PROPERTIES; static final String DOT; static final String SLASH; static final String UTF8; static final String JCR_ROOT; } | @Test public void testParseAndFormat() throws Exception { File inputFile = new File(getClass().getResource("/test-formatted-input.xml").getFile()); File outputFile = File.createTempFile("export-test-", ".xml"); OutputStream outputStream = new FileOutputStream(outputFile); XMLReader reader = XMLReaderFactory.createXMLReader(org.apache.xerces.parsers.SAXParser.class.getName()); DataTransporter.readFormatted(reader, inputFile, outputStream); IOUtils.closeQuietly(outputStream); Reader expectedReader = new InputStreamReader(getClass().getResourceAsStream("/test-formatted-expected.xml")); Reader actualReader = new FileReader(outputFile); DetailedDiff xmlDiff = new DetailedDiff(new Diff(expectedReader, actualReader)); IOUtils.closeQuietly(expectedReader); IOUtils.closeQuietly(actualReader); outputFile.delete(); final StringBuilder diffLog = new StringBuilder(); for (Iterator iter = xmlDiff.getAllDifferences().iterator(); iter.hasNext();) { Difference difference = (Difference) iter.next(); diffLog.append("expected> ").append(difference.getControlNodeDetail().getValue()).append("\n"); diffLog.append("actual > ").append(difference.getTestNodeDetail().getValue()).append("\n"); } assertTrue("Document is not formatted as expected:\n" + diffLog.toString(), xmlDiff.identical()); } |
DataTransporter { protected static void readFormatted(XMLReader reader, File inputFile, OutputStream outputStream) throws FileNotFoundException, IOException, SAXException { InputStream fileInputStream = new FileInputStream(inputFile); readFormatted(reader, fileInputStream, outputStream); IOUtils.closeQuietly(fileInputStream); } static synchronized void importDocument(Document xmlDocument, String repositoryName, String basepath,
boolean keepVersionHistory, int importMode, boolean saveAfterImport,
boolean createBasepathIfNotExist); static synchronized void importFile(File xmlFile, String repositoryName, String basepath,
boolean keepVersionHistory, int importMode, boolean saveAfterImport,
boolean createBasepathIfNotExist); static void executeBootstrapImport(File xmlFile, String repositoryName); static void importProperties(Properties properties, String repositoryName); static synchronized void importXmlStream(InputStream xmlStream, String repositoryName, String basepath,
String name, boolean keepVersionHistory, int importMode,
boolean saveAfterImport, boolean createBasepathIfNotExist); static void executeExport(OutputStream baseOutputStream, boolean keepVersionHistory, boolean format,
Session session, String basepath, String repository, String ext); static void parseAndFormat(OutputStream stream, XMLReader reader, String repository, String basepath,
Session session, boolean noRecurse); static String encodePath(String path, String separator, String enc); static String decodePath(String path, String enc); static String createExportPath(String path); static String revertExportPath(String exportPath); static final String ZIP; static final String GZ; static final String XML; static final String PROPERTIES; static final String DOT; static final String SLASH; static final String UTF8; static final String JCR_ROOT; } | @Test public void testRemoveNs() throws Exception { InputStream input = getClass().getResourceAsStream("/test-unwantedns.xml"); File outputFile = File.createTempFile("export-test-", ".xml"); OutputStream outputStream = new FileOutputStream(outputFile); XMLReader reader = XMLReaderFactory.createXMLReader(org.apache.xerces.parsers.SAXParser.class.getName()); DataTransporter.readFormatted(reader, input, outputStream); IOUtils.closeQuietly(outputStream); String result = FileUtils.readFileToString(outputFile); outputFile.delete(); assertFalse("'removeme' namespace still found in output file", StringUtils.contains(result, "xmlns:removeme")); assertTrue("'sv' namespace not found in output file", StringUtils.contains(result, "xmlns:sv")); assertTrue("'xsi' namespace not found in output file", StringUtils.contains(result, "xmlns:xsi")); } |
DataTransporter { public static String encodePath(String path, String separator, String enc) { StringBuilder pathEncoded = new StringBuilder(); try { if (!StringUtils.contains(path, separator)) { return URLEncoder.encode(path, enc); } for(int i=0; i < path.length(); i++) { String ch = String.valueOf(path.charAt(i)); if(separator.equals(ch)) { pathEncoded.append(ch); } else { pathEncoded.append(URLEncoder.encode(ch, enc)); } } } catch (UnsupportedEncodingException e) { return path; } return pathEncoded.toString(); } static synchronized void importDocument(Document xmlDocument, String repositoryName, String basepath,
boolean keepVersionHistory, int importMode, boolean saveAfterImport,
boolean createBasepathIfNotExist); static synchronized void importFile(File xmlFile, String repositoryName, String basepath,
boolean keepVersionHistory, int importMode, boolean saveAfterImport,
boolean createBasepathIfNotExist); static void executeBootstrapImport(File xmlFile, String repositoryName); static void importProperties(Properties properties, String repositoryName); static synchronized void importXmlStream(InputStream xmlStream, String repositoryName, String basepath,
String name, boolean keepVersionHistory, int importMode,
boolean saveAfterImport, boolean createBasepathIfNotExist); static void executeExport(OutputStream baseOutputStream, boolean keepVersionHistory, boolean format,
Session session, String basepath, String repository, String ext); static void parseAndFormat(OutputStream stream, XMLReader reader, String repository, String basepath,
Session session, boolean noRecurse); static String encodePath(String path, String separator, String enc); static String decodePath(String path, String enc); static String createExportPath(String path); static String revertExportPath(String exportPath); static final String ZIP; static final String GZ; static final String XML; static final String PROPERTIES; static final String DOT; static final String SLASH; static final String UTF8; static final String JCR_ROOT; } | @Test public void testEncodePath() { String pathName = "www.testme.ch/test/me&now"; String encodedPath = DataTransporter.encodePath(pathName, DataTransporter.DOT, DataTransporter.UTF8); assertEquals("www.testme.ch%2Ftest%2Fme%26now", encodedPath); pathName = "www.testme.ch/test.baz/foo..bar/me&now"; encodedPath = DataTransporter.encodePath(pathName, DataTransporter.DOT, DataTransporter.UTF8); assertEquals("www.testme.ch%2Ftest.baz%2Ffoo..bar%2Fme%26now", encodedPath); } |
DataTransporter { public static String createExportPath(String path) { String newPath = path.replace(".", ".."); newPath = newPath.replace("/", "."); return newPath; } static synchronized void importDocument(Document xmlDocument, String repositoryName, String basepath,
boolean keepVersionHistory, int importMode, boolean saveAfterImport,
boolean createBasepathIfNotExist); static synchronized void importFile(File xmlFile, String repositoryName, String basepath,
boolean keepVersionHistory, int importMode, boolean saveAfterImport,
boolean createBasepathIfNotExist); static void executeBootstrapImport(File xmlFile, String repositoryName); static void importProperties(Properties properties, String repositoryName); static synchronized void importXmlStream(InputStream xmlStream, String repositoryName, String basepath,
String name, boolean keepVersionHistory, int importMode,
boolean saveAfterImport, boolean createBasepathIfNotExist); static void executeExport(OutputStream baseOutputStream, boolean keepVersionHistory, boolean format,
Session session, String basepath, String repository, String ext); static void parseAndFormat(OutputStream stream, XMLReader reader, String repository, String basepath,
Session session, boolean noRecurse); static String encodePath(String path, String separator, String enc); static String decodePath(String path, String enc); static String createExportPath(String path); static String revertExportPath(String exportPath); static final String ZIP; static final String GZ; static final String XML; static final String PROPERTIES; static final String DOT; static final String SLASH; static final String UTF8; static final String JCR_ROOT; } | @Test public void testCreateExportPath() throws Exception { String path = DataTransporter.createExportPath("/foo/bar.baz/test../dir/baz..bar"); assertEquals(".foo.bar..baz.test.....dir.baz....bar", path); path = DataTransporter.createExportPath("/"); assertEquals(".", path); } |
DataTransporter { public static String revertExportPath(String exportPath) { if(".".equals(exportPath)) { return "/"; } Matcher matcher = DOT_NAME_PATTERN.matcher(exportPath); StringBuilder reversed = new StringBuilder(exportPath.length()); while(matcher.find()){ String group = matcher.group(); int dotsNumber = StringUtils.countMatches(group, "."); if(dotsNumber == 1) { reversed.append(group.replaceFirst("\\.", "/")); } else { String dots = StringUtils.substringBeforeLast(group, ".").replace("..", "."); String name = StringUtils.substringAfterLast(group, "."); reversed.append(dots); if(dotsNumber % 2 != 0) { reversed.append("/"); } reversed.append(name); } } return reversed.toString(); } static synchronized void importDocument(Document xmlDocument, String repositoryName, String basepath,
boolean keepVersionHistory, int importMode, boolean saveAfterImport,
boolean createBasepathIfNotExist); static synchronized void importFile(File xmlFile, String repositoryName, String basepath,
boolean keepVersionHistory, int importMode, boolean saveAfterImport,
boolean createBasepathIfNotExist); static void executeBootstrapImport(File xmlFile, String repositoryName); static void importProperties(Properties properties, String repositoryName); static synchronized void importXmlStream(InputStream xmlStream, String repositoryName, String basepath,
String name, boolean keepVersionHistory, int importMode,
boolean saveAfterImport, boolean createBasepathIfNotExist); static void executeExport(OutputStream baseOutputStream, boolean keepVersionHistory, boolean format,
Session session, String basepath, String repository, String ext); static void parseAndFormat(OutputStream stream, XMLReader reader, String repository, String basepath,
Session session, boolean noRecurse); static String encodePath(String path, String separator, String enc); static String decodePath(String path, String enc); static String createExportPath(String path); static String revertExportPath(String exportPath); static final String ZIP; static final String GZ; static final String XML; static final String PROPERTIES; static final String DOT; static final String SLASH; static final String UTF8; static final String JCR_ROOT; } | @Test public void testRevertExportPath() throws Exception { String revertedPath = DataTransporter.revertExportPath(".foo.bar..baz.test.....dir.baz....bar"); assertEquals("/foo/bar.baz/test../dir/baz..bar", revertedPath); revertedPath = DataTransporter.revertExportPath(".foo-bar..baz.test"); assertEquals("/foo-bar.baz/test", revertedPath); revertedPath = DataTransporter.revertExportPath(".123..baz.test"); assertEquals("/123.baz/test", revertedPath); revertedPath = DataTransporter.revertExportPath(".-123..baz_test._dir"); assertEquals("/-123.baz_test/_dir", revertedPath); revertedPath = DataTransporter.revertExportPath("baz"); assertEquals("baz", revertedPath); revertedPath = DataTransporter.revertExportPath("config.server.name"); assertEquals("config/server/name", revertedPath); revertedPath = DataTransporter.revertExportPath("."); assertEquals("/", revertedPath); } |
ModuleBootstrapTask extends BootstrapResourcesTask { @Override protected boolean acceptResource(InstallContext ctx, String resourceName) { final String moduleName = ctx.getCurrentModuleDefinition().getName(); return resourceName.startsWith("/mgnl-bootstrap/" + moduleName + "/") && resourceName.endsWith(".xml"); } ModuleBootstrapTask(); } | @Test public void testShouldOnlyBootstrapFilesFromThisModule() { final ModuleDefinition modDef = new ModuleDefinition("test-module", Version.parseVersion("1.0"), null, null); final InstallContext ctx = createStrictMock(InstallContext.class); expect(ctx.getCurrentModuleDefinition()).andReturn(modDef).anyTimes(); replay(ctx); final ModuleBootstrapTask task = new ModuleBootstrapTask(); assertEquals(true, task.acceptResource(ctx, "/mgnl-bootstrap/test-module/foo.xml")); assertEquals(true, task.acceptResource(ctx, "/mgnl-bootstrap/test-module/foo/bar.xml")); assertEquals(false, task.acceptResource(ctx, "/mgnl-bootstrap/test-module-foo.xml")); assertEquals(false, task.acceptResource(ctx, "/mgnl-bootstrap/test-module.xml")); assertEquals(false, task.acceptResource(ctx, "/mgnl-bootstrap/other-module/foo/bar.xml")); assertEquals(false, task.acceptResource(ctx, "/mgnl-pouet/test-module/foo/bar.xml")); assertEquals(false, task.acceptResource(ctx, "/mgnl-pouet/other-module/foo/bar.xml")); assertEquals(false, task.acceptResource(ctx, "/test-module/foo.xml")); assertEquals(false, task.acceptResource(ctx, "/other-module/foo.xml")); verify(ctx); } |
RegisterServletTask extends AbstractTask { @Override public void execute(InstallContext installContext) throws TaskExecutionException { log.debug("Registering servlet " + servletDefinition.getName() + " in servlet filter."); final String servletFilterPath = DEFAULT_SERVLET_FILTER_PATH; try { final Content servletNode = installContext.getConfigHierarchyManager().createContent(servletFilterPath, servletDefinition.getName(), ItemType.CONTENTNODE.getSystemName()); NodeDataUtil.getOrCreateAndSet(servletNode, "class", "info.magnolia.cms.filters.ServletDispatchingFilter"); NodeDataUtil.getOrCreateAndSet(servletNode, "enabled", true); NodeDataUtil.getOrCreateAndSet(servletNode, "servletClass", servletDefinition.getClassName()); NodeDataUtil.getOrCreateAndSet(servletNode, "servletName", servletDefinition.getName()); NodeDataUtil.getOrCreateAndSet(servletNode, "comment", servletDefinition.getComment()); final Content mappingsNode = servletNode.createContent("mappings", ItemType.CONTENTNODE); for (String pattern : servletDefinition.getMappings()) { if (StringUtils.isBlank(pattern)) { installContext.warn("Empty mappings configuration is not supported and servlet was not installed."); continue; } String mappingNodeName = Path.getUniqueLabel(mappingsNode, Path.getValidatedLabel(pattern)); final Content mappingNode = mappingsNode.createContent(mappingNodeName, ItemType.CONTENTNODE); NodeDataUtil.getOrCreateAndSet(mappingNode, "pattern", pattern); } final Content parametersNode = servletNode.createContent("parameters", ItemType.CONTENTNODE); for (ServletParameterDefinition parameter : servletDefinition.getParams()) { NodeDataUtil.getOrCreateAndSet(parametersNode, parameter.getName(), parameter.getValue()); } } catch (RepositoryException e) { log.error("Cannot create servlet node in servlet filter.", e); } } RegisterServletTask(ServletDefinition servletDefinition); @Override void execute(InstallContext installContext); ServletDefinition getServletDefinition(); } | @Test public void testRegisterServletTaskWithEmptyMappings() throws Exception { ServletDefinition sd = new ServletDefinition(); sd.addMapping(""); sd.setName("dummy"); RegisterServletTask task = new RegisterServletTask(sd); ModuleDefinition module = new ModuleDefinition(); module.setName("test"); installContext.setCurrentModule(module); task.execute(installContext); assertEquals(1, installContext.getMessages().size()); final List<InstallContext.Message> messageForTestModule = installContext.getMessages().get(module.toString()); assertEquals(1, messageForTestModule.size()); assertEquals("Empty mappings configuration is not supported and servlet was not installed.", messageForTestModule.get(0).getMessage()); }
@Test public void testRegisterServletTaskWithMappings() throws Exception { ServletDefinition sd = new ServletDefinition(); sd.addMapping(null); sd.setName("dummy"); RegisterServletTask task = new RegisterServletTask(sd); ModuleDefinition module = new ModuleDefinition(); module.setName("test"); installContext.setCurrentModule(module); task.execute(installContext); assertEquals(1, installContext.getMessages().size()); final List<InstallContext.Message> messageForTestModule = installContext.getMessages().get(module.toString()); assertEquals(1, messageForTestModule.size()); assertEquals("Empty mappings configuration is not supported and servlet was not installed.", messageForTestModule.get(0).getMessage()); } |
TextFileConditionsUtil { public void addFalseConditionIfExpressionIsContained(String fileName, String regExp) { List<String> matches = TextFileUtil.getTrimmedLinesMatching(fileName, regExp); if (matches.size() > 0) { conditions.add(new FalseCondition("Invalid entries", "The file '" + fileName + "' contains " + matches.size() + " line(s) matching " + regExp + ". Please remove it.")); } } TextFileConditionsUtil(List<Condition> conditions); void addFalseConditionIfExpressionIsNotContained(String fileName, String regExp); void addFalseConditionIfExpressionIsContained(String fileName, String regExp); } | @Test public void testAddFalseConditionIfExpressionIsContained() { final String file = "src/test/resources/config/outdated-jaas.config"; util.addFalseConditionIfExpressionIsContained(file, "^Jackrabbit.*"); assertEquals(1, conditions.size()); assertTrue(conditions.get(0) instanceof FalseCondition); assertThat(conditions.get(0).getDescription(), Matchers.containsString(file)); assertThat(conditions.get(0).getDescription(), Matchers.endsWith("Please remove it.")); } |
TextFileConditionsUtil { public void addFalseConditionIfExpressionIsNotContained(String fileName, String regExp) { List<String> matches = TextFileUtil.getTrimmedLinesMatching(fileName, regExp); if (matches.isEmpty()) { conditions.add(new FalseCondition("Missing required entries.", "The file '" + fileName + "' must contain a line matching " + regExp + ". Please add it.")); } } TextFileConditionsUtil(List<Condition> conditions); void addFalseConditionIfExpressionIsNotContained(String fileName, String regExp); void addFalseConditionIfExpressionIsContained(String fileName, String regExp); } | @Test public void testAddFalseConditionIfExpressionIsNotContained() { final String file = "src/test/resources/config/current-jaas.config"; util.addFalseConditionIfExpressionIsNotContained(file, "^Jackrabbit.*"); assertEquals(1, conditions.size()); assertTrue(conditions.get(0) instanceof FalseCondition); assertThat(conditions.get(0).getDescription(), Matchers.containsString(file)); assertThat(conditions.get(0).getDescription(), Matchers.endsWith("Please add it.")); } |
WorkspaceXmlConditionsUtil { public void paramAnalyzerIsNotSet() { List<String> names = WorkspaceXmlUtil.getWorkspaceNamesMatching("/Workspace/SearchIndex/param[@name='analyzer']/@value"); if (names.size() > 0) { for (int i = 0; i < names.size(); i++) { conditions.add(new WarnCondition("workspace.xml updates", "Workspace definition in workspace " + names.get(i) + " Should not have an analyzer set - this will lead to error-logs when strarting up your server.")); } } } WorkspaceXmlConditionsUtil(List<Condition> conditions); void workspaceHasOldIndexer(); void textFilterClassesAreNotSet(); void paramAnalyzerIsNotSet(); void accessControlProviderIsSet(); } | @Test public void testParamAnalyzerIsNotAround() { util.paramAnalyzerIsNotSet(); assertEquals(1,conditions.size()); assertTrue(conditions.get(0) instanceof WarnCondition); assertTrue("Received condition was expected to be comming from the outdated config!", conditions.get(0).getDescription().contains("/outdated/workspace.xml")); } |
WorkspaceXmlConditionsUtil { public void textFilterClassesAreNotSet() { List<String> names = WorkspaceXmlUtil.getWorkspaceNamesMatching("/Workspace/SearchIndex/param[@name='textFilterClasses']/@value"); if (names.size() > 0) { for (int i = 0; i < names.size(); i++) { conditions.add(new FalseCondition("workspace.xml updates", "Workspace definition in workspace " + names.get(i) + " references indexer which has changed; please remove the parameter 'textFilterClasses'.")); } } } WorkspaceXmlConditionsUtil(List<Condition> conditions); void workspaceHasOldIndexer(); void textFilterClassesAreNotSet(); void paramAnalyzerIsNotSet(); void accessControlProviderIsSet(); } | @Test public void testTextFilterClassesAreNotSet() { util.textFilterClassesAreNotSet(); assertEquals(1,conditions.size()); assertTrue(conditions.get(0) instanceof FalseCondition); assertTrue("Received condition was expected to be comming from the outdated config!", conditions.get(0).getDescription().contains("/outdated/workspace.xml")); } |
WorkspaceXmlConditionsUtil { public void accessControlProviderIsSet() { List<String> names = WorkspaceXmlUtil.getWorkspaceNames("/Workspace/WorkspaceSecurity/AccessControlProvider/@class", null); if (names.size() > 0) { for (int i = 0; i < names.size(); i++) { conditions.add(new FalseCondition("workspace.xml updates", "Workspace definition in workspace " + names.get(i) + " must have an AccessControlProvider set.")); } } } WorkspaceXmlConditionsUtil(List<Condition> conditions); void workspaceHasOldIndexer(); void textFilterClassesAreNotSet(); void paramAnalyzerIsNotSet(); void accessControlProviderIsSet(); } | @Test public void testAccessControlProviderIsSet() { util.accessControlProviderIsSet(); assertEquals(1,conditions.size()); assertTrue(conditions.get(0) instanceof FalseCondition); assertTrue("Received condition was expected to be comming from the outdated config!", conditions.get(0).getDescription().contains("/outdated/workspace.xml")); } |
PropertyValuesTask extends AbstractTask { protected void checkAndModifyPropertyValue(InstallContext ctx, Content node, String propertyName, String expectedCurrentValue, String newValue) throws RepositoryException { final NodeData prop = node.getNodeData(propertyName); final String currentvalue = prop.getString(); if (prop.isExist() && currentvalue.equals(expectedCurrentValue)) { prop.setValue(newValue); } else { final String msg = format("Property \"{0}\" was expected to exist at {1} with value \"{2}\" but {3,choice,0#does not exist|1#has the value \"{4}\" instead}.", propertyName, node.getHandle(), expectedCurrentValue, Integer.valueOf(prop.isExist() ? 1 : 0), currentvalue); ctx.warn(msg); } } PropertyValuesTask(String name, String description); } | @Test public void testExistingPropertyIsReplaced() throws RepositoryException { final MockContent node = new MockContent("foo"); node.addNodeData("bar", "old-value"); final PropertyValuesTask pvd = new DummyPropertyValuesDelta(); replay(ctx); pvd.checkAndModifyPropertyValue(ctx, node, "bar", "old-value", "newValue"); verify(ctx); final NodeData nodeData = node.getNodeData("bar"); assertEquals("newValue", nodeData.getString()); }
@Test public void testNonExistingPropertyIsNotReplacedButLogged() throws RepositoryException { ctx.warn("Property \"bar\" was expected to exist at /foo with value \"old-value\" but does not exist."); final MockContent node = new MockContent("foo"); final PropertyValuesTask pvd = new DummyPropertyValuesDelta(); replay(ctx); pvd.checkAndModifyPropertyValue(ctx, node, "bar", "old-value", "newValue"); verify(ctx); final NodeData nodeData = node.getNodeData("bar"); assertEquals(false, nodeData.isExist()); }
@Test public void testPropertywithUnexpectedValueIsNotReplacedButLogged() throws RepositoryException { ctx.warn("Property \"bar\" was expected to exist at /foo with value \"old-value\" but has the value \"wrong-value\" instead."); final MockContent node = new MockContent("foo"); node.addNodeData("bar", "wrong-value"); final PropertyValuesTask pvd = new DummyPropertyValuesDelta(); replay(ctx); pvd.checkAndModifyPropertyValue(ctx, node, "bar", "old-value", "newValue"); verify(ctx); final NodeData nodeData = node.getNodeData("bar"); assertEquals("wrong-value", nodeData.getString()); } |
PropertyValuesTask extends AbstractTask { protected void checkAndModifyPartOfPropertyValue(InstallContext ctx, Node node, String propertyName, String expectedValue, String newValue) throws RepositoryException { if(node.hasProperty(propertyName)){ final Property prop = node.getProperty(propertyName); final String currentvalue = prop.getString(); if(currentvalue.contains(expectedValue)) { prop.setValue(StringUtils.replace(currentvalue, expectedValue, newValue)); } else { final String msg = format("Property \"{0}\" was expected to exist at {1} with part string \"{2}\" but does not contain this string.", propertyName, node.getPath(), expectedValue); ctx.warn(msg); } } else { final String msg = format("Property \"{0}\" was expected to exist at {1} with part string \"{2}\" but does not exist.", propertyName, node.getPath(), expectedValue); ctx.warn(msg); } } PropertyValuesTask(String name, String description); } | @Test public void testExistingPropertyWithPartOfStringIsReplaced() throws RepositoryException { final MockNode node = new MockNode("foo"); node.setProperty("bar", "some-old-value"); final PropertyValuesTask pvd = new DummyPropertyValuesDelta(); replay(ctx); pvd.checkAndModifyPartOfPropertyValue(ctx, node, "bar", "old", "new"); verify(ctx); final Property nodeData = node.getProperty("bar"); assertEquals("some-new-value", nodeData.getString()); }
@Test public void testPropertyThatNotContainPartOfStringIsNotReplacedButLogged() throws RepositoryException { ctx.warn("Property \"bar\" was expected to exist at /foo with part string \"old\" but does not contain this string."); final MockNode node = new MockNode("foo"); node.setProperty("bar", "some-wrong-value"); final PropertyValuesTask pvd = new DummyPropertyValuesDelta(); replay(ctx); pvd.checkAndModifyPartOfPropertyValue(ctx, node, "bar", "old", "new"); verify(ctx); final Property nodeData = node.getProperty("bar"); assertEquals("some-wrong-value", nodeData.getString()); }
@Test public void testNonExistingPropertyIsNotReplacedButLogged2() throws RepositoryException { ctx.warn("Property \"bar\" was expected to exist at /foo with part string \"old\" but does not exist."); final MockNode node = new MockNode("foo"); final PropertyValuesTask pvd = new DummyPropertyValuesDelta(); replay(ctx); pvd.checkAndModifyPartOfPropertyValue(ctx, node, "bar", "old", "new"); verify(ctx); assertEquals(false, node.hasProperty("bar")); } |
PropertyValuesTask extends AbstractTask { protected void newProperty(InstallContext ctx, Content node, String propertyName, String value) throws RepositoryException { newProperty(ctx, node, propertyName, value, true); } PropertyValuesTask(String name, String description); } | @Test public void testNonExistingPropertyAndExpectedAsSuchIsCreated() throws RepositoryException { final MockContent node = new MockContent("foo"); final PropertyValuesTask pvd = new DummyPropertyValuesDelta(); replay(ctx); pvd.newProperty(ctx, node, "bar", "newValue"); verify(ctx); final NodeData nodeData = node.getNodeData("bar"); assertEquals("newValue", nodeData.getString()); }
@Test public void testUnexpectedlyExistingPropertyIsNotReplacedAndLogged() throws RepositoryException { ctx.warn("Property \"bar\" was expected not to exist at /foo, but exists with value \"old-value\" and was going to be created with value \"newValue\"."); final MockContent node = new MockContent("foo"); node.addNodeData("bar", "old-value"); final PropertyValuesTask pvd = new DummyPropertyValuesDelta(); replay(ctx); pvd.newProperty(ctx, node, "bar", "newValue"); verify(ctx); } |
PartialBootstrapTask extends AbstractTask { protected String getOutputResourceName(final String resource, final String itemPath) { String inputResourceName = BootstrapUtil.getFilenameFromResource(resource, ".xml"); String tmpitemPath = itemPath.replace("/", "."); tmpitemPath = StringUtils.removeStart(tmpitemPath, "."); tmpitemPath = StringUtils.substringAfter(tmpitemPath, "."); String outputResourceName = inputResourceName + "." + tmpitemPath; if(StringUtils.isNotEmpty(targetResource)) { outputResourceName = targetResource; } return outputResourceName; } PartialBootstrapTask(String name, String description, String resource, String itemPath); PartialBootstrapTask(String name, String description, String resource, String itemPath, String targetResource); PartialBootstrapTask(String name, String description, String resource, String itemPath, String targetResource, int importUUIDBehavior); PartialBootstrapTask(String name, String description, String resource, String itemPath, int importUUIDBehavior); @Override void execute(InstallContext ctx); } | @Test public void testGetOutputResourceName() throws Exception { PartialBootstrapTask task = new PartialBootstrapTask("", "", "/mgnl-bootstrap/form/config.modules.form.dialogs.form.xml", "/form/tabConfirmEmail/confirmContentType"); String outputResourceName = task.getOutputResourceName(task.getResource(), task.getItemPath()); assertEquals("config.modules.form.dialogs.form.tabConfirmEmail.confirmContentType", outputResourceName); task = new PartialBootstrapTask("", "", "/mgnl-bootstrap/form/config.modules.form..baz.dialogs.form.xml", "/form/tabConfirmEmail/confirmContentType.qux"); outputResourceName = task.getOutputResourceName(task.getResource(), task.getItemPath()); assertEquals("config.modules.form..baz.dialogs.form.tabConfirmEmail.confirmContentType..qux", outputResourceName); } |
DependencyLevelComparator implements Comparator<ModuleDefinition> { protected int calcDependencyDepth(ModuleDefinition def) { if (def.getDependencies() == null || def.getDependencies().size() == 0) { return 0; } final List<Integer> dependencyLevels = new ArrayList<Integer>(); for (final DependencyDefinition dep : def.getDependencies()) { final ModuleDefinition depDef = allKnownModulesDefinitions.get(dep.getName()); if (depDef == null && !dep.isOptional()) { throw new RuntimeException("Missing definition for module:" + dep.getName()); } else if (depDef != null) { dependencyLevels.add(Integer.valueOf(calcDependencyDepth(depDef))); } else { dependencyLevels.add(-1); } } return (Collections.max(dependencyLevels)).intValue() + 1; } DependencyLevelComparator(Map<String, ModuleDefinition> allKnownModulesDefinitions); @Override int compare(ModuleDefinition def1, ModuleDefinition def2); } | @Test public void testCalcDependencyLevelWithNonOptionalDependencies() { final ModuleDefinition modDefA = new ModuleDefinition("mod-a", Version.parseVersion("1"), "fake.Module", null); final ModuleDefinition modDefB = new ModuleDefinition("mod-b", Version.parseVersion("1"), "fake.Module", null); final ModuleDefinition modDefC = new ModuleDefinition("mod-c", Version.parseVersion("1"), "fake.Module", null); final DependencyDefinition depOnA = new DependencyDefinition(); depOnA.setName("mod-a"); depOnA.setVersion("1"); final DependencyDefinition depOnB = new DependencyDefinition(); depOnB.setName("mod-b"); depOnB.setVersion("1"); modDefB.addDependency(depOnA); modDefC.addDependency(depOnB); final Map<String, ModuleDefinition> map = new HashMap<String, ModuleDefinition>(); map.put(modDefA.getName(), modDefA); map.put(modDefB.getName(), modDefB); map.put(modDefC.getName(), modDefC); final DependencyLevelComparator reg = new DependencyLevelComparator(map); assertEquals(0, reg.calcDependencyDepth(modDefA)); assertEquals(1, reg.calcDependencyDepth(modDefB)); assertEquals(2, reg.calcDependencyDepth(modDefC)); }
@Test public void testCalcDependencyLevelIgnoresUnregisteredOptionalDependencies() { final ModuleDefinition modDefB = new ModuleDefinition("mod-b", Version.parseVersion("1"), "fake.Module", null); final ModuleDefinition modDefC = new ModuleDefinition("mod-c", Version.parseVersion("1"), "fake.Module", null); final DependencyDefinition depOnA = new DependencyDefinition(); depOnA.setName("mod-a"); depOnA.setVersion("1"); depOnA.setOptional(true); final DependencyDefinition depOnB = new DependencyDefinition(); depOnB.setName("mod-b"); depOnB.setVersion("1"); modDefC.addDependency(depOnA); modDefC.addDependency(depOnB); final Map<String, ModuleDefinition> map = new HashMap<String, ModuleDefinition>(); map.put(modDefB.getName(), modDefB); map.put(modDefC.getName(), modDefC); final DependencyLevelComparator reg = new DependencyLevelComparator(map); assertEquals(0, reg.calcDependencyDepth(modDefB)); assertEquals(1, reg.calcDependencyDepth(modDefC)); }
@Test public void testCalcDependencyLevelDoesNotIgnoreRegisteredOptionalDependencies() { final ModuleDefinition modDefA = new ModuleDefinition("mod-a", Version.parseVersion("1"), "fake.Module", null); final ModuleDefinition modDefB = new ModuleDefinition("mod-b", Version.parseVersion("1"), "fake.Module", null); final ModuleDefinition modDefC = new ModuleDefinition("mod-c", Version.parseVersion("1"), "fake.Module", null); final DependencyDefinition depOnA = new DependencyDefinition(); depOnA.setName("mod-a"); depOnA.setVersion("1"); depOnA.setOptional(true); final DependencyDefinition depOnB = new DependencyDefinition(); depOnB.setName("mod-b"); depOnB.setVersion("1"); modDefB.addDependency(depOnA); modDefC.addDependency(depOnA); modDefC.addDependency(depOnB); final Map<String, ModuleDefinition> map = new HashMap<String, ModuleDefinition>(); map.put(modDefA.getName(), modDefA); map.put(modDefB.getName(), modDefB); map.put(modDefC.getName(), modDefC); final DependencyLevelComparator reg = new DependencyLevelComparator(map); assertEquals(0, reg.calcDependencyDepth(modDefA)); assertEquals(1, reg.calcDependencyDepth(modDefB)); assertEquals(2, reg.calcDependencyDepth(modDefC)); }
@Test public void testCanHandleOnlyOptionalAndMissingDependencies() { final ModuleDefinition modDefA = new ModuleDefinition("mod-a", Version.parseVersion("1"), "fake.Module", null); final DependencyDefinition optDepOnX = new DependencyDefinition(); optDepOnX.setName("mod-x"); optDepOnX.setVersion("1"); optDepOnX.setOptional(true); final DependencyDefinition optDepOnY = new DependencyDefinition(); optDepOnY.setName("mod-y"); optDepOnY.setVersion("1"); optDepOnY.setOptional(true); modDefA.addDependency(optDepOnX); modDefA.addDependency(optDepOnY); final Map<String, ModuleDefinition> map = new HashMap<String, ModuleDefinition>(); map.put(modDefA.getName(), modDefA); final DependencyLevelComparator reg = new DependencyLevelComparator(map); assertEquals(0, reg.calcDependencyDepth(modDefA)); }
@Test public void testCalcDependencyLevelWithNoDependencies() { final ModuleDefinition modDefA = new ModuleDefinition("mod-a", Version.parseVersion("1"), "fake.Module", null); final Map<String, ModuleDefinition> map = new HashMap<String, ModuleDefinition>(); map.put(modDefA.getName(), modDefA); final DependencyLevelComparator reg = new DependencyLevelComparator(map); assertEquals(0, reg.calcDependencyDepth(modDefA)); } |
DependencyCheckerImpl implements DependencyChecker { @Override public void checkDependencies(Map<String, ModuleDefinition> moduleDefinitions) throws ModuleDependencyException { for (ModuleDefinition def : moduleDefinitions.values()) { for (DependencyDefinition dep : def.getDependencies()) { checkSpecificDependency(def, dep, moduleDefinitions); } } } @Override void checkDependencies(Map<String, ModuleDefinition> moduleDefinitions); @Override List<ModuleDefinition> sortByDependencyLevel(Map<String, ModuleDefinition> moduleDefinitions); } | @Test public void testSimpleDependenciesAreResolvedAndChecked() throws Exception { final Map modules = buildModulesMapWithDependencyOn("3.0"); depChecker.checkDependencies(modules); }
@Test public void testDependenciesCanUseLowerBoundInfiniteRanges() throws Exception { final Map modules = buildModulesMapWithDependencyOn("*/4.0"); depChecker.checkDependencies(modules); }
@Test public void testDependenciesCanUseUpperBoundInfiniteRanges() throws Exception { final Map modules = buildModulesMapWithDependencyOn("1.0/*"); depChecker.checkDependencies(modules); }
@Test public void testDependenciesCanUseFiniteRanges() throws Exception { final Map modules = buildModulesMapWithDependencyOn("1.0/4.0"); depChecker.checkDependencies(modules); }
@Test public void testDependenciesShouldBeInvalidIfOutsideOfUpperBound() { final Map modules = buildModulesMapWithDependencyOn("1.0/2.0"); try { depChecker.checkDependencies(modules); fail("should have failed"); } catch (ModuleDependencyException e) { assertEquals("Module module2 (version 1.2.0) is dependent on module1 version 1.0/2.0, but module1 (version 3.0.0) is currently installed.", e.getMessage()); } }
@Test public void testDependenciesShouldBeInvalidIfOutsideOfLowerBound() { final Map modules = buildModulesMapWithDependencyOn("4.0/5.0"); try { depChecker.checkDependencies(modules); fail("should have failed"); } catch (ModuleDependencyException e) { assertEquals("Module module2 (version 1.2.0) is dependent on module1 version 4.0/5.0, but module1 (version 3.0.0) is currently installed.", e.getMessage()); } }
@Test public void testDependenciesShouldBeInvalidIfOutsideOfUpperBoundWithInfiniteLowerBound() { final Map modules = buildModulesMapWithDependencyOn("*/2.0"); try { depChecker.checkDependencies(modules); fail("should have failed"); } catch (ModuleDependencyException e) { assertEquals("Module module2 (version 1.2.0) is dependent on module1 version */2.0, but module1 (version 3.0.0) is currently installed.", e.getMessage()); } }
@Test public void testDependenciesShouldBeInvalidIfOutsideOfLowerBoundWithInfiniteUpperBound() { final Map modules = buildModulesMapWithDependencyOn("4.0/*"); try { depChecker.checkDependencies(modules); fail("should have failed"); } catch (ModuleDependencyException e) { assertEquals("Module module2 (version 1.2.0) is dependent on module1 version 4.0/*, but module1 (version 3.0.0) is currently installed.", e.getMessage()); } }
@Test public void testShouldFailWhenDependencyNotFound() { final Map modules = buildModulesMapWithDependencyOn("Q.W"); modules.remove("module1"); try { depChecker.checkDependencies(modules); fail("should have failed"); } catch (ModuleDependencyException e) { assertEquals("Module module2 (version 1.2.0) is dependent on module1 version Q.W, which was not found.", e.getMessage()); } }
@Test public void testOptionalDependenciesStillHaveToMatchVersionRanges() throws ModuleDependencyException { final ModuleDefinition modDefB = new ModuleDefinition("mod-b", Version.parseVersion("1.5"), "fake.Module", null); final ModuleDefinition modDefC = new ModuleDefinition("mod-c", Version.parseVersion("1"), "fake.Module", null); final DependencyDefinition depOnB = new DependencyDefinition(); depOnB.setName("mod-b"); depOnB.setVersion("1.0/1.2"); depOnB.setOptional(true); modDefC.addDependency(depOnB); final Map<String, ModuleDefinition> map = new HashMap<String, ModuleDefinition>(); map.put(modDefB.getName(), modDefB); map.put(modDefC.getName(), modDefC); try { depChecker.checkDependencies(map); fail("should have failed"); } catch (ModuleDependencyException e) { assertEquals("Module mod-c (version 1.0.0) is dependent on mod-b version 1.0/1.2, but mod-b (version 1.5.0) is currently installed.", e.getMessage()); } }
@Test public void testBlowupExplicitelyInCaseOfSelfDependency() { final ModuleDefinition modDefA = new ModuleDefinition("mod-a", Version.parseVersion("1"), "fake.Module", null); modDefA.setDisplayName("Module-A"); final DependencyDefinition depOnSelf = new DependencyDefinition(); depOnSelf.setName("mod-a"); depOnSelf.setVersion("1"); modDefA.addDependency(depOnSelf); final Map<String, ModuleDefinition> map = new HashMap<String, ModuleDefinition>(); map.put(modDefA.getName(), modDefA); try { depChecker.checkDependencies(map); fail("should have failed"); } catch (Throwable e) { assertTrue("Should have failed with a ModuleDependencyException instead of " + e.toString(), ModuleDependencyException.class.equals(e.getClass())); assertEquals("Cyclic dependency between Module-A (version 1.0.0) and Module-A (version 1.0.0)", e.getMessage()); } }
@Test public void testCyclicDependenciesBlowupWithAClearExceptionMessage() { final ModuleDefinition modDefA = new ModuleDefinition("mod-a", Version.parseVersion("1"), "fake.Module", null); modDefA.setDisplayName("Module-A"); final ModuleDefinition modDefB = new ModuleDefinition("mod-b", Version.parseVersion("1"), "fake.Module", null); modDefB.setDisplayName("Module-B"); final DependencyDefinition depOnA = new DependencyDefinition(); depOnA.setName("mod-a"); depOnA.setVersion("1"); final DependencyDefinition depOnB = new DependencyDefinition(); depOnB.setName("mod-b"); depOnB.setVersion("1"); modDefA.addDependency(depOnB); modDefB.addDependency(depOnA); final Map<String, ModuleDefinition> map = new HashMap<String, ModuleDefinition>(); map.put(modDefA.getName(), modDefA); map.put(modDefB.getName(), modDefB); try { depChecker.checkDependencies(map); fail("should have failed"); } catch (Throwable e) { assertTrue("Should have failed with a ModuleDependencyException instead of " + e.toString(), ModuleDependencyException.class.equals(e.getClass())); assertEquals("Cyclic dependency between Module-A (version 1.0.0) and Module-B (version 1.0.0)", e.getMessage()); } } |
TemplatingFunctions { public boolean isInherited(Node content) { if (content instanceof InheritanceNodeWrapper) { return ((InheritanceNodeWrapper) content).isInherited(); } return false; } @Inject TemplatingFunctions(Provider<AggregationState> aggregationStateProvider); Node asJCRNode(ContentMap contentMap); ContentMap asContentMap(Node content); List<Node> children(Node content); List<Node> children(Node content, String nodeTypeName); List<ContentMap> children(ContentMap content); List<ContentMap> children(ContentMap content, String nodeTypeName); ContentMap root(ContentMap contentMap); ContentMap root(ContentMap contentMap, String nodeTypeName); Node root(Node content); Node root(Node content, String nodeTypeName); ContentMap parent(ContentMap contentMap); ContentMap parent(ContentMap contentMap, String nodeTypeName); Node parent(Node content); Node parent(Node content, String nodeTypeName); ContentMap page(ContentMap content); Node page(Node content); List<ContentMap> ancestors(ContentMap contentMap); List<ContentMap> ancestors(ContentMap contentMap, String nodeTypeName); List<Node> ancestors(Node content); List<Node> ancestors(Node content, String nodeTypeName); Node inherit(Node content); Node inherit(Node content, String relPath); ContentMap inherit(ContentMap content); ContentMap inherit(ContentMap content, String relPath); Property inheritProperty(Node content, String relPath); Property inheritProperty(ContentMap content, String relPath); List<Node> inheritList(Node content, String relPath); List<ContentMap> inheritList(ContentMap content, String relPath); boolean isInherited(Node content); boolean isInherited(ContentMap content); boolean isFromCurrentPage(Node content); boolean isFromCurrentPage(ContentMap content); String link(String workspace, String nodeIdentifier); @Deprecated String link(Property property); String link(Node content); String link(ContentMap contentMap); String language(); String externalLink(Node content, String linkPropertyName); String externalLink(ContentMap content, String linkPropertyName); String externalLinkTitle(Node content, String linkPropertyName, String linkTitlePropertyName); String externalLinkTitle(ContentMap content, String linkPropertyName, String linkTitlePropertyName); boolean isEditMode(); boolean isPreviewMode(); boolean isAuthorInstance(); boolean isPublicInstance(); String createHtmlAttribute(String name, String value); SiblingsHelper siblings(Node node); SiblingsHelper siblings(ContentMap node); Node content(String path); Node content(String repository, String path); Node contentByIdentifier(String id); Node contentByIdentifier(String repository, String id); List<ContentMap> asContentMapList(Collection<Node> nodeList); List<Node> asNodeList(Collection<ContentMap> contentMapList); ContentMap decode(ContentMap content); Node decode(Node content); Node encode(Node content); String metaData(Node content, String property); String metaData(ContentMap content, String property); Collection<Node> search(String workspace, String statement, String language, String returnItemType); Collection<Node> simpleSearch(String workspace, String statement, String returnItemType, String startPath); } | @Test public void testNodeIsInherited() throws RepositoryException { InheritanceNodeWrapper inheritedNode = wrapNodeForInheritance(childPageSubPage); assertTrue(functions.isInherited(inheritedNode.getNode("comp-L2-1"))); assertTrue(functions.isInherited(inheritedNode.getNode("comp-L2-2"))); assertTrue(functions.isInherited(inheritedNode.getNode("comp-L2-3"))); }
@Test public void testContentMapIsInherited() throws RepositoryException { InheritanceNodeWrapper inheritedNode = wrapNodeForInheritance(childPageSubPage); assertTrue(functions.isInherited(new ContentMap(inheritedNode.getNode("comp-L2-1")))); assertTrue(functions.isInherited(new ContentMap(inheritedNode.getNode("comp-L2-2")))); assertTrue(functions.isInherited(new ContentMap(inheritedNode.getNode("comp-L2-3")))); } |
DependencyCheckerImpl implements DependencyChecker { @Override public List<ModuleDefinition> sortByDependencyLevel(Map<String, ModuleDefinition> moduleDefinitions) { final List<ModuleDefinition> modules = new ArrayList<ModuleDefinition>(moduleDefinitions.values()); Collections.sort(modules, new DependencyLevelComparator(moduleDefinitions)); return modules; } @Override void checkDependencies(Map<String, ModuleDefinition> moduleDefinitions); @Override List<ModuleDefinition> sortByDependencyLevel(Map<String, ModuleDefinition> moduleDefinitions); } | @Test public void testModulesShouldBeSortedAccordingToDependencies() { final Map modules = new HashMap(); final ModuleDefinition module1 = new ModuleDefinition("module1", Version.parseVersion("3.0"), null, null); final ModuleDefinition module2 = new ModuleDefinition("module2", Version.parseVersion("3.0"), null, null); module2.addDependency(new DependencyDefinition("module1", "3.0", false)); final ModuleDefinition module3 = new ModuleDefinition("module3", Version.parseVersion("3.0"), null, null); module3.addDependency(new DependencyDefinition("module1", "3.0", false)); module3.addDependency(new DependencyDefinition("module2", "3.0", false)); final ModuleDefinition module4 = new ModuleDefinition("module4", Version.parseVersion("3.0"), null, null); module4.addDependency(new DependencyDefinition("module1", "3.0", false)); module4.addDependency(new DependencyDefinition("module3", "3.0", false)); final ModuleDefinition module5 = new ModuleDefinition("module5", Version.parseVersion("3.0"), null, null); module5.addDependency(new DependencyDefinition("module2", "3.0", false)); modules.put("module5", module5); modules.put("module4", module4); modules.put("module3", module3); modules.put("module2", module2); modules.put("module1", module1); final List list = depChecker.sortByDependencyLevel(modules); assertEquals(5, list.size()); assertEquals(module1, list.get(0)); assertEquals(module2, list.get(1)); assertEquals(module3, list.get(2)); assertEquals(module5, list.get(3)); assertEquals(module4, list.get(4)); }
@Test public void testCoreIsAlwaysSortedFirst() { final Map modules = new HashMap(); final ModuleDefinition core = new ModuleDefinition("core", Version.parseVersion("1.2.3"), null, null); final ModuleDefinition module1 = new ModuleDefinition("a_module1", Version.parseVersion("3.0"), null, null); final ModuleDefinition module2 = new ModuleDefinition("a_module2", Version.parseVersion("3.0"), null, null); final ModuleDefinition module3 = new ModuleDefinition("a_module3", Version.parseVersion("3.0"), null, null); module2.addDependency(new DependencyDefinition("a_module1", "3.0", false)); module3.addDependency(new DependencyDefinition("core", "3.0", false)); modules.put("a_module3", module3); modules.put("a_module2", module2); modules.put("a_module1", module1); modules.put("core", core); final List list = depChecker.sortByDependencyLevel(modules); assertEquals(4, list.size()); assertEquals(core, list.get(0)); assertEquals(module1, list.get(1)); assertEquals(module2, list.get(2)); assertEquals(module3, list.get(3)); }
@Test public void testWebappIsAlwaysSortedLast() { final Map modules = new HashMap(); final ModuleDefinition webapp = new ModuleDefinition("webapp", Version.parseVersion("1.2.3"), null, null); final ModuleDefinition core = new ModuleDefinition("core", Version.parseVersion("1.2.3"), null, null); final ModuleDefinition module1 = new ModuleDefinition("a_module1", Version.parseVersion("3.0"), null, null); final ModuleDefinition module2 = new ModuleDefinition("a_module2", Version.parseVersion("3.0"), null, null); final ModuleDefinition module3 = new ModuleDefinition("a_module3", Version.parseVersion("3.0"), null, null); module2.addDependency(new DependencyDefinition("a_module1", "3.0", false)); module3.addDependency(new DependencyDefinition("core", "3.0", false)); modules.put("a_module3", module3); modules.put("a_module2", module2); modules.put("a_module1", module1); modules.put("core", core); modules.put("webapp", webapp); final List list = depChecker.sortByDependencyLevel(modules); assertEquals(5, list.size()); assertEquals(core, list.get(0)); assertEquals(module1, list.get(1)); assertEquals(module2, list.get(2)); assertEquals(module3, list.get(3)); assertEquals(webapp, list.get(4)); } |
TemplatingFunctions { public boolean isFromCurrentPage(Node content) { return !isInherited(content); } @Inject TemplatingFunctions(Provider<AggregationState> aggregationStateProvider); Node asJCRNode(ContentMap contentMap); ContentMap asContentMap(Node content); List<Node> children(Node content); List<Node> children(Node content, String nodeTypeName); List<ContentMap> children(ContentMap content); List<ContentMap> children(ContentMap content, String nodeTypeName); ContentMap root(ContentMap contentMap); ContentMap root(ContentMap contentMap, String nodeTypeName); Node root(Node content); Node root(Node content, String nodeTypeName); ContentMap parent(ContentMap contentMap); ContentMap parent(ContentMap contentMap, String nodeTypeName); Node parent(Node content); Node parent(Node content, String nodeTypeName); ContentMap page(ContentMap content); Node page(Node content); List<ContentMap> ancestors(ContentMap contentMap); List<ContentMap> ancestors(ContentMap contentMap, String nodeTypeName); List<Node> ancestors(Node content); List<Node> ancestors(Node content, String nodeTypeName); Node inherit(Node content); Node inherit(Node content, String relPath); ContentMap inherit(ContentMap content); ContentMap inherit(ContentMap content, String relPath); Property inheritProperty(Node content, String relPath); Property inheritProperty(ContentMap content, String relPath); List<Node> inheritList(Node content, String relPath); List<ContentMap> inheritList(ContentMap content, String relPath); boolean isInherited(Node content); boolean isInherited(ContentMap content); boolean isFromCurrentPage(Node content); boolean isFromCurrentPage(ContentMap content); String link(String workspace, String nodeIdentifier); @Deprecated String link(Property property); String link(Node content); String link(ContentMap contentMap); String language(); String externalLink(Node content, String linkPropertyName); String externalLink(ContentMap content, String linkPropertyName); String externalLinkTitle(Node content, String linkPropertyName, String linkTitlePropertyName); String externalLinkTitle(ContentMap content, String linkPropertyName, String linkTitlePropertyName); boolean isEditMode(); boolean isPreviewMode(); boolean isAuthorInstance(); boolean isPublicInstance(); String createHtmlAttribute(String name, String value); SiblingsHelper siblings(Node node); SiblingsHelper siblings(ContentMap node); Node content(String path); Node content(String repository, String path); Node contentByIdentifier(String id); Node contentByIdentifier(String repository, String id); List<ContentMap> asContentMapList(Collection<Node> nodeList); List<Node> asNodeList(Collection<ContentMap> contentMapList); ContentMap decode(ContentMap content); Node decode(Node content); Node encode(Node content); String metaData(Node content, String property); String metaData(ContentMap content, String property); Collection<Node> search(String workspace, String statement, String language, String returnItemType); Collection<Node> simpleSearch(String workspace, String statement, String returnItemType, String startPath); } | @Test public void testNodeIsFromCurrentPage() throws RepositoryException { InheritanceNodeWrapper inheritedNode = wrapNodeForInheritance(childPage); assertTrue(functions.isFromCurrentPage(inheritedNode.getNode("comp-L3-1"))); }
@Test public void testContentMapIsFromCurrentPage() throws RepositoryException { InheritanceNodeWrapper inheritedNode = wrapNodeForInheritance(childPage); assertTrue(functions.isFromCurrentPage(new ContentMap(inheritedNode.getNode("comp-L3-1")))); } |
BetwixtModuleDefinitionReader implements ModuleDefinitionReader { @Override public ModuleDefinition read(Reader in) throws ModuleManagementException { try { final Reader replacedDtd = replaceDtd(in); return (ModuleDefinition) beanReader.parse(replacedDtd); } catch (IOException e) { throw new ModuleManagementException("Can't read module definition file: " + e.getMessage(), e); } catch (SAXException e) { throw new ModuleManagementException(e.getMessage(), e); } } BetwixtModuleDefinitionReader(); @Override Map<String, ModuleDefinition> readAll(); @Override ModuleDefinition read(Reader in); @Override ModuleDefinition readFromResource(String resourcePath); } | @Test public void testDisplayNameCanBeWrittenWithDashEventhoughThisIsDeprecated() throws Exception { String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<module>\n" + " <name>the name</name>\n" + " <display-name>The Display Name</display-name>" + " <class>foo</class>\n" + " <versionHandler>java.lang.String</versionHandler>\n" + " <version>1.0</version>\n" + "</module>"; ModuleDefinition mod = new BetwixtModuleDefinitionReader().read(new StringReader(xml)); assertEquals("The Display Name", mod.getDisplayName()); }
@Test public void testDisplayNameShouldBeWrittenWithCapitalN() throws Exception { String xml = "<module>\n" + " <name>the name</name>\n" + " <displayName>The Display Name</displayName>\n" + " <class>foo</class>\n" + " <versionHandler>java.lang.String</versionHandler>\n" + " <version>1.0</version>\n" + "</module>"; ModuleDefinition mod = new BetwixtModuleDefinitionReader().read(new StringReader(xml)); assertEquals("The Display Name", mod.getDisplayName()); }
@Test public void testClassIsResolvedToClassNameAsAString() throws Exception { String xml = "<module>\n" + " <name>the name</name>\n" + " <class>java.lang.Integer</class>\n" + " <versionHandler>java.lang.String</versionHandler>\n" + " <version>1.0</version>\n" + "</module>"; ModuleDefinition mod = new BetwixtModuleDefinitionReader().read(new StringReader(xml)); assertEquals("java.lang.Integer", mod.getClassName()); }
@Test public void testVersionHandlerIsResolvedToAClass() throws Exception { String xml = "<module>\n" + " <name>the name</name>\n" + " <class>java.lang.Integer</class>\n" + " <versionHandler>java.lang.String</versionHandler>" + " <version>1.0</version>\n" + "</module>"; ModuleDefinition mod = new BetwixtModuleDefinitionReader().read(new StringReader(xml)); assertEquals(String.class, mod.getVersionHandler()); }
@Test public void testModuleVersionIsProperlyRead() throws ModuleManagementException { String xml = "<module>\n" + " <name>the name</name>\n" + " <class>foo</class>\n" + " <versionHandler>java.lang.String</versionHandler>\n" + " <version>1.2.3</version>\n" + "</module>"; final ModuleDefinition def = new BetwixtModuleDefinitionReader().read(new StringReader(xml)); final Version version = def.getVersion(); assertNotNull(version); assertEquals("1.2.3", version.toString()); VersionTest.assertVersion(1, 2, 3, null, version); }
@Test public void testDependenciesVersionAreProperlyRead() throws ModuleManagementException { String xml = "<module>\n" + " <name>myName</name>\n" + " <class>foo</class>\n" + " <versionHandler>java.lang.String</versionHandler>\n" + " <version>1.2.3</version>\n" + " <dependencies>\n" + " <dependency>\n" + " <name>foo</name>\n" + " <version>2.3.4/*</version>\n" + " <optional>true</optional>\n" + " </dependency>\n" + " <dependency>\n" + " <name>bar</name>\n" + " <version>5.6.7/8.9.0</version>\n" + " </dependency>\n" + " </dependencies>\n" + "</module>"; final ModuleDefinition def = new BetwixtModuleDefinitionReader().read(new StringReader(xml)); final Collection deps = def.getDependencies(); assertEquals(2, deps.size()); final Iterator it = deps.iterator(); final DependencyDefinition dep1 = (DependencyDefinition) it.next(); final DependencyDefinition dep2 = (DependencyDefinition) it.next(); assertEquals("foo", dep1.getName()); assertEquals(true, dep1.isOptional()); assertEquals("2.3.4/*", dep1.getVersion()); final VersionRange dep1versionRange = dep1.getVersionRange(); assertNotNull(dep1versionRange); assertEquals("2.3.4/*", dep1versionRange.toString()); VersionTest.assertVersion(2, 3, 4, null, dep1versionRange.getFrom()); assertEquals(Version.UNDEFINED_TO, dep1versionRange.getTo()); assertEquals("bar", dep2.getName()); assertEquals(false, dep2.isOptional()); assertEquals("5.6.7/8.9.0", dep2.getVersion()); final VersionRange dep2versionRange = dep2.getVersionRange(); assertNotNull(dep2versionRange); assertEquals("5.6.7/8.9.0", dep2versionRange.toString()); VersionTest.assertVersion(5, 6, 7, null, dep2versionRange.getFrom()); VersionTest.assertVersion(8, 9, 0, null, dep2versionRange.getTo()); }
@Test public void testDependenciesCanBeSpecifiedWithoutVersion() throws ModuleManagementException { String xml = "<module>\n" + " <name>myName</name>\n" + " <version>1.2.3</version>\n" + " <dependencies>\n" + " <dependency>\n" + " <name>foo</name>\n" + " <optional>true</optional>\n" + " </dependency>\n" + " <dependency>\n" + " <name>bar</name>\n" + " </dependency>\n" + " </dependencies>\n" + "</module>"; final ModuleDefinition def = new BetwixtModuleDefinitionReader().read(new StringReader(xml)); final List<DependencyDefinition> deps = new ArrayList<DependencyDefinition>(def.getDependencies()); assertEquals(2, deps.size()); final DependencyDefinition dep1 = deps.get(0); final DependencyDefinition dep2 = deps.get(1); assertEquals("foo", dep1.getName()); assertEquals(true, dep1.isOptional()); assertEquals(null, dep1.getVersion()); final VersionRange dep1versionRange = dep1.getVersionRange(); assertEquals(Version.UNDEFINED_FROM, dep1versionRange.getFrom()); assertEquals(Version.UNDEFINED_TO, dep1versionRange.getTo()); assertEquals("bar", dep2.getName()); assertEquals(false, dep2.isOptional()); assertEquals(null, dep2.getVersion()); final VersionRange dep2versionRange = dep2.getVersionRange(); assertEquals(Version.UNDEFINED_FROM, dep2versionRange.getFrom()); assertEquals(Version.UNDEFINED_TO, dep2versionRange.getTo()); }
@Test public void testInvalidXmlIsCheckedAgainstDTD() { String xmlWithVersionElementMisplaced = "<module>\n" + " <version>2.3.4</version>\n" + " <name>the name</name>\n" + "</module>"; try { new BetwixtModuleDefinitionReader().read(new StringReader(xmlWithVersionElementMisplaced)); fail("should have failed"); } catch (ModuleManagementException e) { assertEquals("Invalid module definition file, error at line 6 column 10: The content of element type \"module\" must match \"(name,(displayName|display-name)?,description?,class?,versionHandler?,version,properties?,components*,dependencies?,servlets?,repositories?)\".", e.getMessage()); } }
@Test public void testGivenDtdIsIgnoredAndCheckedAgainstOurs() { String xmlWithWrongDtd = "<!DOCTYPE log4j:configuration SYSTEM \"log4j.dtd\">\n" + "<module>\n" + " <version>2.3.4</version>\n" + " <name>the name</name>\n" + "</module>"; try { new BetwixtModuleDefinitionReader().read(new StringReader(xmlWithWrongDtd)); fail("should have failed"); } catch (ModuleManagementException e) { assertEquals("Invalid module definition file, error at line 6 column 10: The content of element type \"module\" must match \"(name,(displayName|display-name)?,description?,class?,versionHandler?,version,properties?,components*,dependencies?,servlets?,repositories?)\".", e.getMessage()); } } |
BetwixtModuleDefinitionReader implements ModuleDefinitionReader { @Override public ModuleDefinition readFromResource(String resourcePath) throws ModuleManagementException { final InputStreamReader reader = new InputStreamReader(getClass().getResourceAsStream(resourcePath)); try { return read(reader); } finally { try { reader.close(); } catch (IOException e) { log.error("Can't close input for " + resourcePath); } } } BetwixtModuleDefinitionReader(); @Override Map<String, ModuleDefinition> readAll(); @Override ModuleDefinition read(Reader in); @Override ModuleDefinition readFromResource(String resourcePath); } | @Test public void testReadCompleteDescriptorAndCheckAllPropertiesDamnYouBetwixt() throws Exception { final BetwixtModuleDefinitionReader reader = new BetwixtModuleDefinitionReader(); final ModuleDefinition m = reader.readFromResource("/info/magnolia/module/model/reader/dummy-module.xml"); assertNotNull(m); assertEquals("dummy", m.getName()); assertEquals("dummy module", m.getDisplayName()); assertEquals("a dummy module descriptor for tests", m.getDescription()); assertEquals(BetwixtModuleDefinitionReaderTest.class.getName(), m.getClassName()); assertEquals(DependencyCheckerImplTest.class, m.getVersionHandler()); assertEquals("7.8.9", m.getVersion().toString()); assertNotNull(m.getProperties()); assertEquals(2, m.getProperties().size()); assertEquals("bar", m.getProperty("foo")); assertEquals("lolo", m.getProperty("lala")); assertNotNull(m.getDependencies()); assertEquals(2, m.getDependencies().size()); assertNotNull(m.getServlets()); assertEquals(2, m.getServlets().size()); final ServletDefinition servlet1 = (ServletDefinition) fromList(m.getServlets(), 0); assertNotNull(servlet1); assertEquals("AServlet", servlet1.getName()); assertEquals(DependencyLevelComparatorTest.class.getName(), servlet1.getClassName()); assertEquals("lalala", servlet1.getComment()); assertEquals(2, servlet1.getMappings().size()); assertEquals("/foo/*", fromList(servlet1.getMappings(), 0)); assertEquals("/bar", fromList(servlet1.getMappings(), 1)); final ServletDefinition servlet2 = (ServletDefinition) fromList(m.getServlets(), 1); assertNotNull(servlet2); assertEquals("OtherServlet", servlet2.getName()); assertEquals(info.magnolia.module.model.VersionComparatorTest.class.getName(), servlet2.getClassName()); assertEquals("blahblah", servlet2.getComment()); assertEquals(1, servlet2.getMappings().size()); assertEquals("/blah/*", fromList(servlet2.getMappings(), 0)); assertNotNull(m.getRepositories()); assertEquals(2, m.getRepositories().size()); final RepositoryDefinition repo1 = (RepositoryDefinition) fromList(m.getRepositories(), 0); assertEquals("some-repo", repo1.getName()); assertEquals(2, repo1.getWorkspaces().size()); assertEquals("workspace-a", fromList(repo1.getWorkspaces(), 0)); assertEquals("workspace-b", fromList(repo1.getWorkspaces(), 1)); assertEquals(null, repo1.getNodeTypeFile()); final RepositoryDefinition repo2 = (RepositoryDefinition) fromList(m.getRepositories(), 1); assertEquals("other-repo", repo2.getName()); assertEquals(1, repo2.getWorkspaces().size()); assertEquals("bleh", fromList(repo2.getWorkspaces(), 0)); assertEquals("/chalala/testNodeTypes.xml", repo2.getNodeTypeFile()); }
@Test public void testReadModuleDescriptorWithComponents() throws ModuleManagementException { final BetwixtModuleDefinitionReader reader = new BetwixtModuleDefinitionReader(); final ModuleDefinition m = reader.readFromResource("/info/magnolia/module/model/reader/dummy-module-with-components.xml"); assertNotNull(m); assertEquals(1, m.getComponents().size()); ComponentsDefinition components = m.getComponents().iterator().next(); assertEquals("platform", components.getId()); assertEquals(2, components.getConfigurers().size()); Iterator<ConfigurerDefinition> iterator = components.getConfigurers().iterator(); ConfigurerDefinition configurer = iterator.next(); assertEquals("com.acme.FirstTestConfigurer", configurer.getClassName()); configurer = iterator.next(); assertEquals("com.acme.SecondTestConfigurer", configurer.getClassName()); assertEquals(1, components.getComponents().size()); ComponentDefinition componentDefinition = components.getComponents().iterator().next(); assertEquals("com.acme.ComponentKey", componentDefinition.getType()); assertEquals("session", componentDefinition.getScope()); assertEquals("impl", componentDefinition.getImplementation()); assertEquals("provider", componentDefinition.getProvider()); assertEquals("true", componentDefinition.getObserved()); assertEquals("config", componentDefinition.getWorkspace()); assertEquals("/modules/acme/foo", componentDefinition.getPath()); assertEquals(1, components.getTypeMappings().size()); TypeMappingDefinition typeMapping = components.getTypeMappings().iterator().next(); assertEquals("t-m-key", typeMapping.getType()); assertEquals("t-m-impl", typeMapping.getImplementation()); } |
Version { public static Version parseVersion(String versionStr) { versionStr = versionStr.trim(); log.debug("parsing version [{}]", versionStr); if (UndefinedDevelopmentVersion.isDevelopmentVersion(versionStr)) { return UNDEFINED_DEVELOPMENT_VERSION; } return new Version(versionStr); } protected Version(int major, int minor, int patch); private Version(String versionStr); static Version parseVersion(String versionStr); static Version parseVersion(int major, int minor, int patch); boolean isEquivalent(final Version other); boolean isStrictlyAfter(final Version other); boolean isBeforeOrEquivalent(final Version other); short getMajor(); short getMinor(); short getPatch(); String getClassifier(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); static final Version UNDEFINED_FROM; static final Version UNDEFINED_TO; static final Version UNDEFINED_DEVELOPMENT_VERSION; } | @Test public void testShouldSupportSingleDigitVersions() { assertVersion(3, 0, 0, null, Version.parseVersion("3")); }
@Test public void testShouldSupportTwoDigitVersions() { assertVersion(3, 0, 0, null, Version.parseVersion("3.0")); assertVersion(3, 1, 0, null, Version.parseVersion("3.1")); }
@Test public void testShouldSupportThreeDigitVersions() { assertVersion(3, 0, 0, null, Version.parseVersion("3.0.0")); assertVersion(3, 2, 0, null, Version.parseVersion("3.2.0")); assertVersion(3, 4, 5, null, Version.parseVersion("3.4.5")); }
@Test public void testShouldSupportAlphanumericClassifiers() { assertVersion(3, 0, 0, "x", Version.parseVersion("3.0.0-x")); assertVersion(3, 0, 0, "Y", Version.parseVersion("3.0.0-Y")); assertVersion(3, 0, 0, "5", Version.parseVersion("3.0.0-5")); assertVersion(3, 0, 0, "20060622gregYO", Version.parseVersion("3.0.0-20060622gregYO")); }
@Test public void testShouldSupportUnderscoresAndDashesInClassifiersToo() { assertVersion(3, 4, 5, "20060622-greg-YO", Version.parseVersion("3.4.5-20060622-greg-YO")); assertVersion(3, 4, 5, "20071102_fixed", Version.parseVersion("3.4.5-20071102_fixed")); }
@Test public void testShouldRejectInvalidCharsInClassifiers() { try { Version.parseVersion("3.0.0-/slash+plus"); fail("should have failed"); } catch (RuntimeException e) { assertEquals("Invalid classifier: \"/slash+plus\" in version \"3.0.0-/slash+plus\"", e.getMessage()); } }
@Test public void testShouldSupportClassifierIndependentlyOfTheVersionNumberPrecision() { assertVersion(3, 0, 0, "foo", Version.parseVersion("3-foo")); assertVersion(3, 0, 0, "foo", Version.parseVersion("3.0-foo")); assertVersion(3, 0, 0, "foo", Version.parseVersion("3.0.0-foo")); assertVersion(3, 1, 0, "foo", Version.parseVersion("3.1-foo")); assertVersion(3, 1, 0, "foo", Version.parseVersion("3.1.0-foo")); assertVersion(3, 1, 7, "foo", Version.parseVersion("3.1.7-foo")); }
@Test public void testShouldTrimInput() { assertVersion(3, 1, 7, "foo", Version.parseVersion(" 3.1.7-foo\t\n ")); } |
VersionComparator implements Comparator<Version> { @Override public int compare(Version v1, Version v2) { if (v1.isStrictlyAfter(v2)) { return 1; } else if (v1.isEquivalent(v2)) { return 0; } else { return -1; } } @Override int compare(Version v1, Version v2); } | @Test public void testBasic() { final VersionComparator vc = new VersionComparator(); assertTrue(vc.compare(V101, V100) > 0); assertTrue(vc.compare(V110, V100) > 0); assertTrue(vc.compare(V200, V100) > 0); assertTrue(vc.compare(V110, V101) > 0); assertTrue(vc.compare(V200, V101) > 0); assertTrue(vc.compare(V200, V110) > 0); assertTrue(vc.compare(V100, V100) == 0); assertTrue(vc.compare(V101, V101) == 0); assertTrue(vc.compare(V110, V110) == 0); assertTrue(vc.compare(V200, V200) == 0); assertTrue(vc.compare(V100, V101) < 0); assertTrue(vc.compare(V100, V110) < 0); assertTrue(vc.compare(V100, V200) < 0); assertTrue(vc.compare(V101, V110) < 0); assertTrue(vc.compare(V101, V200) < 0); assertTrue(vc.compare(V110, V200) < 0); }
@Test public void testClassifiersAreIgnored() { final VersionComparator vc = new VersionComparator(); assertTrue(vc.compare(Version.parseVersion("1.0-foo"), V100) == 0); assertTrue(vc.compare(V100, Version.parseVersion("1.0-bar")) == 0); assertTrue(vc.compare(V100, Version.parseVersion("2.0-bar")) < 0); assertTrue(vc.compare(Version.parseVersion("2.0.5-foo"), V101) > 0); } |
ModuleManagerImpl implements ModuleManager { protected void installOrUpdateModule(ModuleAndDeltas moduleAndDeltas, InstallContextImpl ctx) { final ModuleDefinition moduleDef = moduleAndDeltas.getModule(); final List<Delta> deltas = moduleAndDeltas.getDeltas(); ctx.setCurrentModule(moduleDef); log.debug("Install/update for {} is starting: {}", moduleDef, moduleAndDeltas); applyDeltas(moduleDef, deltas, ctx); log.debug("Install/update for {} has finished", moduleDef, moduleAndDeltas); } @Deprecated protected ModuleManagerImpl(); @Deprecated protected ModuleManagerImpl(InstallContextImpl installContext, ModuleDefinitionReader moduleDefinitionReader); @Inject ModuleManagerImpl(InstallContextImpl installContext, ModuleDefinitionReader moduleDefinitionReader, ModuleRegistry moduleRegistry, DependencyChecker dependencyChecker, Node2BeanProcessor nodeToBean); @Override List<ModuleDefinition> loadDefinitions(); @Override void checkForInstallOrUpdates(); @Override ModuleManagementState getStatus(); @Override ModuleManagerUI getUI(); @Override void performInstallOrUpdate(); @Override InstallContext getInstallContext(); @Override void startModules(); @Override void stopModules(); } | @Test public void testUpdateAppliesSuppliedDeltasAndTasks() throws Exception { final String newVersion = "2.3.4"; final InstallContextImpl ctx = createStrictMock(InstallContextImpl.class); final ModuleDefinition mod = new ModuleDefinition("foo", Version.parseVersion(newVersion), null, null); final Content allModulesNode = createStrictMock(Content.class); final Content moduleNode = createStrictMock(Content.class); final NodeData versionProp = createStrictMock(NodeData.class); final Delta d1 = createStrictMock(Delta.class); final Delta d2 = createStrictMock(Delta.class); final Task t1 = createStrictMock(Task.class); final Task t2 = createStrictMock(Task.class); final Task t3 = createStrictMock(Task.class); final Task t4 = createStrictMock(Task.class); final Version fromVersion = Version.parseVersion("1.2.3"); ctx.setCurrentModule(mod); expect(d2.getTasks()).andReturn(Arrays.asList(t3, t4)); expect(d1.getTasks()).andReturn(Arrays.asList(t1, t2)); t1.execute(ctx); ctx.incExecutedTaskCount(); t2.execute(ctx); ctx.incExecutedTaskCount(); t3.execute(ctx); ctx.incExecutedTaskCount(); t4.execute(ctx); ctx.incExecutedTaskCount(); ctx.setCurrentModule(null); replay(ctx, d1, d2, t1, t2, t3, t4, moduleNode, versionProp, allModulesNode); final ModuleManager.ModuleAndDeltas moduleAndDeltas = new ModuleManager.ModuleAndDeltas(mod, fromVersion, Arrays.asList(d1, d2)); new ModuleManagerImpl(null, null, null, null, null).installOrUpdateModule(moduleAndDeltas, ctx); verify(ctx, d1, d2, t1, t2, t3, t4, moduleNode, versionProp, allModulesNode); }
@Test public void testTaskExecutionExceptionInterruptsTasksAddsExplicitErrorMessage() throws TaskExecutionException { final ModuleDefinition mod = new ModuleDefinition("foo", Version.parseVersion("2.3.4"), null, null); final InstallContextImpl ctx = createStrictMock(InstallContextImpl.class); final Delta d1 = createStrictMock(Delta.class); final Task t1 = createStrictMock(Task.class); final Task t2 = createStrictMock(Task.class); ctx.setCurrentModule(mod); expect(d1.getTasks()).andReturn(Arrays.asList(t1, t2)); t1.execute(ctx); expectLastCall().andThrow(new TaskExecutionException("boo")); expect(t1.getName()).andReturn("task#1").anyTimes(); ctx.error(eq("Could not install or update foo module. Task 'task#1' failed. (TaskExecutionException: boo)"), isA(TaskExecutionException.class)); ctx.setCurrentModule(null); replay(ctx, d1, t1, t2); final ModuleManager.ModuleAndDeltas moduleAndDeltas = new ModuleManager.ModuleAndDeltas(mod, Version.parseVersion("1.2.3"), Arrays.asList(d1)); new ModuleManagerImpl().installOrUpdateModule(moduleAndDeltas, ctx); verify(ctx, d1, t1, t2); } |
ModuleManagerWebUI implements ModuleManagerUI { protected void performInstallOrUpdate() { final Runnable runnable = new Runnable() { @Override public void run() { try { moduleManager.performInstallOrUpdate(); } catch (Throwable e) { log.error("Could not perform installation: " + e.getMessage(), e); moduleManager.getInstallContext().error("Could not perform installation: " + e.getMessage(), e); } } }; new Thread(runnable).start(); } ModuleManagerWebUI(ModuleManager moduleManager); @Override void onStartup(); @Override boolean execute(Writer out, String command); @Override void renderTempPage(Writer out); static final String INSTALLER_PATH; } | @Test public void testModuleManagementExceptionsArePropagatedEvenThoughTheUpdateIsRunningInASeparateThread() throws ModuleManagementException, InterruptedException { final InstallContextImpl ctx = new InstallContextImpl(new ModuleRegistryImpl()); final ModuleManager moduleManager = createStrictMock(ModuleManager.class); moduleManager.performInstallOrUpdate(); expectLastCall().andThrow(new IllegalStateException("boo!")); expect(moduleManager.getInstallContext()).andReturn(ctx); replay(moduleManager); final ModuleManagerWebUI ui = new ModuleManagerWebUI(moduleManager); ui.performInstallOrUpdate(); Thread.sleep(1000); verify(moduleManager); assertEquals(1, ctx.getMessages().size()); final List messagesForNoModule = (ctx.getMessages().get("General messages")); assertEquals(1, messagesForNoModule.size()); final InstallContext.Message msg = (InstallContext.Message) messagesForNoModule.get(0); assertEquals("Could not perform installation: boo!", msg.getMessage()); assertEquals(InstallContext.MessagePriority.error, msg.getPriority()); } |
ModuleLifecycleContextImpl implements ModuleLifecycleContext { @Override public void registerModuleObservingComponent(String nodeName, ObservedManager component) { if (components.containsKey(nodeName)) { final Object currentObservedManager = components.get(nodeName); throw new IllegalStateException("ObservedManager " + currentObservedManager + " was already registered for nodes of name " + nodeName + ", " + component + " can't be registered."); } components.put(nodeName, component); } ModuleLifecycleContextImpl(); @Override void registerModuleObservingComponent(String nodeName, ObservedManager component); void start(Collection<Content> moduleNodes); @Override ModuleDefinition getCurrentModuleDefinition(); void setCurrentModuleDefinition(ModuleDefinition currentModuleDefinition); @Override int getPhase(); void setPhase(int phase); } | @Test public void testCantRegisterAComponentIfNodeNameIsAlreadyForAnotherComponent() { final ModuleLifecycleContextImpl lifecycleCtx = new ModuleLifecycleContextImpl(); lifecycleCtx.registerModuleObservingComponent("foo", new DummyObservedManager1()); try { lifecycleCtx.registerModuleObservingComponent("foo", new DummyObservedManager2()); fail("should have failed"); } catch (IllegalStateException e) { assertEquals("ObservedManager DummyObservedManager1 was already registered for nodes of name foo, DummyObservedManager2 can't be registered.", e.getMessage()); } } |
AbstractModuleVersionHandler implements ModuleVersionHandler { protected void register(Delta delta) { final Version v = delta.getVersion(); if (allDeltas.containsKey(v)) { throw new IllegalStateException("Version " + v + " was already registered in this ModuleVersionHandler."); } delta.getTasks().addAll(getDefaultUpdateTasks(v)); delta.getConditions().addAll(getDefaultUpdateConditions(v)); allDeltas.put(v, delta); } AbstractModuleVersionHandler(); @Override Version getCurrentlyInstalled(InstallContext ctx); @Override List<Delta> getDeltas(InstallContext installContext, Version from); @Override Delta getStartupDelta(InstallContext installContext); } | @Test public void testCantRegisterMultipleDeltasForSameVersion() { final Delta d1 = DeltaBuilder.update(Version.parseVersion("1.0.0"), "", new NullTask("", "")); final Delta d2 = DeltaBuilder.update(Version.parseVersion("1.0.0"), "", new NullTask("", "")); final AbstractModuleVersionHandler versionHandler = newTestModuleVersionHandler(); versionHandler.register(d1); try { versionHandler.register(d2); fail("should have failed"); } catch (IllegalStateException e) { assertEquals("Version 1.0.0 was already registered in this ModuleVersionHandler.", e.getMessage()); } } |
TemplatingFunctions { public Node inherit(Node content) throws RepositoryException { return inherit(content, null); } @Inject TemplatingFunctions(Provider<AggregationState> aggregationStateProvider); Node asJCRNode(ContentMap contentMap); ContentMap asContentMap(Node content); List<Node> children(Node content); List<Node> children(Node content, String nodeTypeName); List<ContentMap> children(ContentMap content); List<ContentMap> children(ContentMap content, String nodeTypeName); ContentMap root(ContentMap contentMap); ContentMap root(ContentMap contentMap, String nodeTypeName); Node root(Node content); Node root(Node content, String nodeTypeName); ContentMap parent(ContentMap contentMap); ContentMap parent(ContentMap contentMap, String nodeTypeName); Node parent(Node content); Node parent(Node content, String nodeTypeName); ContentMap page(ContentMap content); Node page(Node content); List<ContentMap> ancestors(ContentMap contentMap); List<ContentMap> ancestors(ContentMap contentMap, String nodeTypeName); List<Node> ancestors(Node content); List<Node> ancestors(Node content, String nodeTypeName); Node inherit(Node content); Node inherit(Node content, String relPath); ContentMap inherit(ContentMap content); ContentMap inherit(ContentMap content, String relPath); Property inheritProperty(Node content, String relPath); Property inheritProperty(ContentMap content, String relPath); List<Node> inheritList(Node content, String relPath); List<ContentMap> inheritList(ContentMap content, String relPath); boolean isInherited(Node content); boolean isInherited(ContentMap content); boolean isFromCurrentPage(Node content); boolean isFromCurrentPage(ContentMap content); String link(String workspace, String nodeIdentifier); @Deprecated String link(Property property); String link(Node content); String link(ContentMap contentMap); String language(); String externalLink(Node content, String linkPropertyName); String externalLink(ContentMap content, String linkPropertyName); String externalLinkTitle(Node content, String linkPropertyName, String linkTitlePropertyName); String externalLinkTitle(ContentMap content, String linkPropertyName, String linkTitlePropertyName); boolean isEditMode(); boolean isPreviewMode(); boolean isAuthorInstance(); boolean isPublicInstance(); String createHtmlAttribute(String name, String value); SiblingsHelper siblings(Node node); SiblingsHelper siblings(ContentMap node); Node content(String path); Node content(String repository, String path); Node contentByIdentifier(String id); Node contentByIdentifier(String repository, String id); List<ContentMap> asContentMapList(Collection<Node> nodeList); List<Node> asNodeList(Collection<ContentMap> contentMapList); ContentMap decode(ContentMap content); Node decode(Node content); Node encode(Node content); String metaData(Node content, String property); String metaData(ContentMap content, String property); Collection<Node> search(String workspace, String statement, String language, String returnItemType); Collection<Node> simpleSearch(String workspace, String statement, String returnItemType, String startPath); } | @Test public void testInheritFromNode() throws RepositoryException { Node node = functions.inherit(childPage, "comp-L3-1"); assertNodeEqualsNode(childPageComponent, node); }
@Test public void testInheritFromNodeNoContent() throws RepositoryException { Node content = null; Node node = functions.inherit(content, "comp-L3-1"); assertEquals(node, null); }
@Test public void testInheritFromNodeOnlyContent() throws RepositoryException { Node node = functions.inherit(childPage); assertEquals(node.getPath(), childPage.getPath()); assertEquals(node.getIdentifier(), childPage.getIdentifier()); }
@Test public void testInheritedNodeIsUnwrapped() throws RepositoryException { Node node = functions.inherit(childPage, "comp-L3-1"); assertFalse(node instanceof InheritanceNodeWrapper); }
@Test public void testInheritFromContentMap() throws RepositoryException { ContentMap contentMap = functions.inherit(childPageContentMap, "comp-L3-1"); assertMapEqualsMap(childPageComponentContentMap, contentMap); }
@Test public void testInheritFromContentMapOnlyContentMap() throws RepositoryException { ContentMap contentMap = functions.inherit(childPageContentMap); assertEquals(childPageContentMap.getJCRNode().getParent().getPath(), contentMap.getJCRNode().getParent().getPath()); assertEquals(childPageContentMap.getJCRNode().getPath(), contentMap.getJCRNode().getPath()); assertEquals(childPageContentMap.getJCRNode().getIdentifier(), contentMap.getJCRNode().getIdentifier()); }
@Test public void testNonExistingInheritedRelPathShouldReturnNull() throws RepositoryException { ContentMap resultContentMap = functions.inherit(childPageContentMap, "iMaybeExistSomewhereElseButNotHere"); Node node = functions.inherit(childPage, "iMaybeExistSomewhereElseButNotHere"); assertNull(resultContentMap); assertNull(node); } |
AbstractModuleVersionHandler implements ModuleVersionHandler { @Override public List<Delta> getDeltas(InstallContext installContext, Version from) { if (from == null) { return Collections.singletonList(getInstall(installContext)); } return getUpdateDeltas(installContext, from); } AbstractModuleVersionHandler(); @Override Version getCurrentlyInstalled(InstallContext ctx); @Override List<Delta> getDeltas(InstallContext installContext, Version from); @Override Delta getStartupDelta(InstallContext installContext); } | @Test public void testRetrievesTheAppropriateListOfDeltas() { final List deltas = versionHandler.getDeltas(makeInstallContext("1.3"), Version.parseVersion("1.0.1")); assertEquals(3, deltas.size()); assertEquals(d3, deltas.get(0)); assertEquals(d4, deltas.get(1)); assertEquals(d5, deltas.get(2)); }
@Test public void testHasExtraDeltaIfVersionBeingInstalledIsNewerThanLatestRegisteredDelta() { final List deltas = versionHandler.getDeltas(makeInstallContext("1.5"), Version.parseVersion("1.0.1")); assertEquals(4, deltas.size()); assertEquals(d3, deltas.get(0)); assertEquals(d4, deltas.get(1)); assertEquals(d5, deltas.get(2)); assertDefaultUpdateDelta((Delta) deltas.get(3)); }
@Test public void testRetrievesTheAppropriateDeltaForIntermediateUnregisteredVersion() { final List deltas = versionHandler.getDeltas(makeInstallContext("1.5"), Version.parseVersion("1.2.5")); assertEquals(2, deltas.size()); assertEquals(d5, deltas.get(0)); assertDefaultUpdateDelta((Delta) deltas.get(1)); }
@Test public void testReturnsDefaultUpdateDeltaIfNoDeltaWasRegisteredForNewerVersion() { final List deltas = versionHandler.getDeltas(makeInstallContext("1.5"), Version.parseVersion("1.4")); assertNotNull(deltas); assertEquals(1, deltas.size()); final Delta d = (Delta) deltas.get(0); assertDefaultUpdateDelta(d); }
@Test public void testReturnsEmptyListIfLatestDeltaWasRegisteredForCurrentVersion() { final List deltas = versionHandler.getDeltas(makeInstallContext("1.3"), Version.parseVersion("1.3")); assertNotNull(deltas); assertEquals(0, deltas.size()); }
@Test public void testReturnsEmptyListIfCurrentVersionIsInstalledVersion() { final List deltas = versionHandler.getDeltas(makeInstallContext("1.5"), Version.parseVersion("1.5")); assertEquals(0, deltas.size()); }
@Test public void testReturnsDefaultUpdateDeltaIfNoDeltaWasRegisteredAtAll() { final AbstractModuleVersionHandler versionHandler = newTestModuleVersionHandler(); final List deltas = versionHandler.getDeltas(makeInstallContext("1.5"), Version.parseVersion("1.0.1")); assertNotNull(deltas); assertEquals(1, deltas.size()); assertDefaultUpdateDelta((Delta) deltas.get(0)); }
@Test public void testDeltasAreSorted() { final List deltas = versionHandler.getDeltas(makeInstallContext("0.5"), Version.parseVersion("0.4")); assertEquals(6, deltas.size()); assertEquals(d1, deltas.get(0)); assertEquals(d2, deltas.get(1)); assertEquals(d3, deltas.get(2)); assertEquals(d4, deltas.get(3)); assertEquals(d5, deltas.get(4)); assertDefaultUpdateDelta((Delta) deltas.get(5)); } |
ModuleRegistryImpl implements ModuleRegistry { @Override public List<ModuleDefinition> getModuleDefinitions() { final List<ModuleDefinition> defs = new ArrayList<ModuleDefinition>(); for (ModuleEntry mod : entries.values()) { defs.add(mod.moduleDefinition); } return Collections.unmodifiableList(defs); } ModuleRegistryImpl(); @Override void registerModuleDefinition(String name, ModuleDefinition moduleDefinition); @Override void registerModuleInstance(String name, Object moduleInstance); @Override void registerModuleVersionHandler(String name, ModuleVersionHandler moduleVersionHandler); @Override boolean isModuleRegistered(String name); @Override ModuleDefinition getDefinition(String name); @Override Object getModuleInstance(String name); @Override T getModuleInstance(final Class<T> moduleClass); @Override ModuleVersionHandler getVersionHandler(String name); @Override Set<String> getModuleNames(); @Override List<ModuleDefinition> getModuleDefinitions(); } | @Test public void testModuleDefinitionsAreListedInDependencyOrder() throws ModuleManagementException { final ModuleDefinition a = new ModuleDefinition("a", Version.parseVersion("1.0"), null, null); final ModuleDefinition b = new ModuleDefinition("b", Version.parseVersion("1.0"), null, null); final ModuleDefinition c = new ModuleDefinition("c", Version.parseVersion("1.0"), null, null); b.addDependency(new DependencyDefinition("a", "1.0", false)); c.addDependency(new DependencyDefinition("a", "1.0", false)); c.addDependency(new DependencyDefinition("b", "1.0", false)); final ModuleRegistryImpl moduleRegistry = new ModuleRegistryImpl(); final ModuleManagerImpl moduleManager = new ModuleManagerImpl(null, new FixedModuleDefinitionReader(c, b, a), moduleRegistry, new DependencyCheckerImpl(), null); moduleManager.loadDefinitions(); final List<ModuleDefinition> result = moduleRegistry.getModuleDefinitions(); assertEquals(3, result.size()); assertEquals("a", result.get(0).getName()); assertEquals("b", result.get(1).getName()); assertEquals("c", result.get(2).getName()); } |
RenameACLNodesTask extends AbstractRepositoryTask { public RenameACLNodesTask() { super("Security", "Renames ACL nodes."); } RenameACLNodesTask(); } | @Test public void testRenameACLNodesTask() throws Exception { Session session = MgnlContext.getSystemContext().getJCRSession(RepositoryConstants.USER_ROLES); Node roleNode = session.getRootNode().addNode("superuser", NodeTypes.Role.NAME); roleNode.addNode("acl_dms_dms", NodeTypes.ContentNode.NAME); roleNode.addNode("acl_website", NodeTypes.ContentNode.NAME); roleNode.addNode("something_else_completely", NodeTypes.ContentNode.NAME); InstallContext installContext = mock(InstallContext.class); when(installContext.getJCRSession(RepositoryConstants.USER_ROLES)).thenReturn(session); RenameACLNodesTask task = new RenameACLNodesTask(); task.execute(installContext); session.getNode("/superuser/acl_dms"); session.getNode("/superuser/acl_website"); session.getNode("/superuser/something_else_completely"); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.