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 ...
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 (patternL...
@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); Ac...
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> ch...
@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.NA...
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> per...
@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.cla...
ContentRepository { public static Provider getRepositoryProvider(String repositoryOrLogicalWorkspace) { RepositoryManager repositoryManager = Components.getComponent(RepositoryManager.class); if (!repositoryManager.hasRepository(repositoryOrLogicalWorkspace)) { repositoryOrLogicalWorkspace = getMappedRepositoryName(rep...
@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 ...
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(); boolea...
@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...
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,...
@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.addSessi...
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(Str...
@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 getCharacterEnc...
@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(); assertT...
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();...
@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 setUnActivate...
@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(); C...
@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(); vo...
@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(); ...
@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(...
@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 setUn...
@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, Access...
@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 setCreatio...
@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 se...
@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.Activatabl...
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(...
@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 va...
@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.LastMo...
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 setUnActiv...
@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_MOD...
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 setUnA...
@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 setU...
@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.LAS...
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 ...
@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 setUnActiva...
@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)); assertNot...
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 setUnAc...
@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 igno...
@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.Rendera...
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(); ...
@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")...
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 val...
@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 te...
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 ...
@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 != '?' && charCo...
@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...
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 getCache...
@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....
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 getTempDirect...
@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(); } }; } Versioned...
@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.get...
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 isInv...
@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 mi...
@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 mgnlMixDel...
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 Cont...
@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.setAttrib...
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); pro...
@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()); assertEq...
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); fina...
@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(versionedCo...
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 DefaultConten...
@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 fir...
ContentTypeFilter extends AbstractMgnlFilter { protected String setupContentTypeAndCharacterEncoding(String extension, HttpServletRequest request, HttpServletResponse response) { final String mimeType = MIMEMapping.getMIMETypeOrDefault(extension); final String characterEncoding = MIMEMapping.getContentEncodingOrDefault...
@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 In...
@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); ...
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(); c...
@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 testChannelFromResolverG...
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 = requ...
@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"); InterceptF...
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); isSe...
@Test public void testContentIsServedFromOutputStreamInNewRequestAfterHeadRequestWasExecuted() throws IOException, ServletException { final HttpServletRequest request = mock(HttpServletRequest.class); final HttpServletResponse response = mock(HttpServletResponse.class); final DummyFilter dummy = new DummyFilter(); fina...
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 Il...
@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 'd...
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 RepositoryMappingDe...
@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.getWorkspa...
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.cre...
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.createNo...
@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.ex...
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 Valu...
@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", "z...
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 NodeOperati...
@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("no...
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 (cont...
@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("f...
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 NodeOperat...
@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...
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 ...
@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).getIte...
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 cr...
@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 = contex...
@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 nodeDa...
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)...
@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....
@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"); Si...
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 voi...
@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; } }); f...
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.current...
@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)...
@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:crea...
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); } el...
@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...
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(ful...
@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.substringAfte...
@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...
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.substringBe...
@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 { 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, "/"); } ret...
@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);...
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.xer...
@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.createXMLRe...
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(fileInputS...
@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.xerc...
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...
@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 = DataT...
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, ...
@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 = StringU...
@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/t...
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"); } Modul...
@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(...
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 =...
@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.setCurr...
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....
@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(condition...
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 cont...
@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(cond...
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", "Workspa...
@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/workspa...
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 upd...
@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...
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", ...
@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...
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 (p...
@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"); v...
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 curren...
@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",...
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.getNo...
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, ".");...
@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.getItemP...
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.g...
@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 ...
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,...
@Test public void testSimpleDependenciesAreResolvedAndChecked() throws Exception { final Map modules = buildModulesMapWithDependencyOn("3.0"); depChecker.checkDependencies(modules); } @Test public void testDependenciesCanUseLowerBoundInfiniteRanges() throws Exception { final Map modules = buildModulesMapWithDependencyO...
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); ContentMa...
@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.isInher...
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 DependencyLevelComparato...
@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); ...
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(N...
@Test public void testNodeIsFromCurrentPage() throws RepositoryException { InheritanceNodeWrapper inheritedNode = wrapNodeForInheritance(childPage); assertTrue(functions.isFromCurrentPage(inheritedNode.getNode("comp-L3-1"))); } @Test public void testContentMapIsFromCurrentPage() throws RepositoryException { Inheritance...
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("...
@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</...
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 { ...
@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...
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...
@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 testShou...
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) ...
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 ...
@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 allModulesNod...
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.getIns...
@Test public void testModuleManagementExceptionsArePropagatedEvenThoughTheUpdateIsRunningInASeparateThread() throws ModuleManagementException, InterruptedException { final InstallContextImpl ctx = new InstallContextImpl(new ModuleRegistryImpl()); final ModuleManager moduleManager = createStrictMock(ModuleManager.class)...
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 " +...
@Test public void testCantRegisterAComponentIfNodeNameIsAlreadyForAnotherComponent() { final ModuleLifecycleContextImpl lifecycleCtx = new ModuleLifecycleContextImpl(); lifecycleCtx.registerModuleObservingComponent("foo", new DummyObservedManager1()); try { lifecycleCtx.registerModuleObservingComponent("foo", new Dummy...
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(getDefaultUpdat...
@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 = newTestModu...
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<N...
@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...
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(); @Overri...
@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 tes...
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); } ModuleRegistryI...
@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 = ...
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("ac...