src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
DelegateNodeWrapper implements Node, Cloneable { public Node deepUnwrap(Class<? extends DelegateNodeWrapper> wrapper) { if (this.getClass().equals(wrapper)) { return getWrappedNode(); } Node next = getWrappedNode(); if (!(next instanceof DelegateNodeWrapper)) { return this; } Node deepUnwrappedNext = ((DelegateNodeWrap...
@Test public void testDeepUnwrap() throws RepositoryException { DelegateNodeWrapper test = new FirstDelegate(new SecondDelegate(new MockNode("test"))); assertTrue(test instanceof FirstDelegate); assertTrue(test.getWrappedNode() instanceof SecondDelegate); DelegateNodeWrapper unwrapped = (DelegateNodeWrapper) test.deepU...
InheritanceNodeWrapper extends ChildWrappingNodeWrapper { @Override public Property getProperty(String relPath) throws PathNotFoundException, RepositoryException { try { if (getWrappedNode().hasProperty(relPath)) { return getWrappedNode().getProperty(relPath); } Node inherited = getNodeSafely(findNextAnchor(), resolveI...
@Test(expected=RepositoryException.class) public void testRoot() throws Exception { setUpNode("testPropertyInheritance"); Node root = new InheritanceNodeWrapper(session.getRootNode()); root.getProperty("whateverThatIsNotOnTheNodeItself"); } @Test public void testPropertyInheritance() throws Exception { setUpNode("testP...
InheritanceNodeWrapper extends ChildWrappingNodeWrapper { @Override public Node getNode(String relPath) throws PathNotFoundException, RepositoryException { Node inherited = getNodeSafely(relPath); if (inherited == null || !filter.evaluateTyped(inherited)) { throw new PathNotFoundException("Can't inherit a node [" + rel...
@Test public void testNestedComponentInheritance() throws Exception { setUpNode("testNestedComponentInheritance"); Node page11 = getWrapped("/page1/page11"); Node page12 = getWrapped("/page1/page12"); Node containerPage11 = page11.getNode("container"); Node containerPage12 = page12.getNode("container"); assertEquals("/...
CommandsManager extends ObservedManager { Catalog getCatalogByName(String name) { return catalogs.get(name); } @Inject CommandsManager(Node2BeanProcessor nodeToBean); Command getCommand(String catalogName, String commandName); Command getCommand(String commandName); @Deprecated static CommandsManager getInstance(); bo...
@Test public void testRegisterCommands() throws Exception { Catalog defaultCatalog = commandsManager.getCatalogByName("default"); assertEquals(2, getCatalogSize(defaultCatalog)); Catalog bazCatalog = commandsManager.getCatalogByName("baz"); assertEquals(2, getCatalogSize(bazCatalog)); }
CommandsManager extends ObservedManager { public Command getCommand(String catalogName, String commandName) { MgnlCatalog catalog = catalogs.get(StringUtils.isNotEmpty(catalogName) ? catalogName : DEFAULT_CATALOG); if (catalog != null) { Command command = catalog.getCommand(commandName); try { if (command != null) { re...
@Test public void testGetCommandByCatalogAndName() throws Exception { Command defaultFoo = commandsManager.getCommand("default", "foo"); Command bazFoo = commandsManager.getCommand("baz", "foo"); assertNotNull(defaultFoo); assertNotNull(bazFoo); assertNotEquals(defaultFoo, bazFoo); }
CommandsManager extends ObservedManager { public boolean executeCommand(final String catalogName, final String commandName, final Map<String, Object> params) throws Exception { final Command command = getCommand(catalogName, commandName); if (command == null) { throw new Exception(String.format("Command [%s] could not ...
@Test public void testExecuteCommand() throws Exception { Map<String,Object> params = new HashMap<String, Object>(); params.put("mustRead", "Die Welt als Wille und Vorstellung"); TestMgnlCommand testCommand = (TestMgnlCommand) commandsManager.getCommand("default", "foo"); assertNull(testCommand.getContext()); commandsM...
RuleBasedCommand extends BaseRepositoryCommand { public Rule getRule() { if (rule == null) { rule = new Rule(); String[] nodeTypes = StringUtils.split(this.getItemTypes(), " ,"); for (int i = 0; i < nodeTypes.length; i++) { String nodeType = nodeTypes[i]; rule.addAllowType(nodeType); } rule.addAllowType(NodeTypes.MetaD...
@Test public void testDefaultRule() throws Exception { Rule rule = cmd.getRule(); assertTrue(rule.isAllowed(content)); assertTrue(rule.isAllowed(resource)); assertTrue(rule.isAllowed(metadata)); assertFalse(rule.isAllowed(folder)); assertFalse(rule.isAllowed(page)); }
RuleBasedCommand extends BaseRepositoryCommand { public void setItemTypes(String nodeTypes) { this.itemTypes = nodeTypes; } Rule getRule(); String getItemTypes(); void setItemTypes(String nodeTypes); void setRule(Rule rule); @Override void release(); static final String ATTRIBUTE_RULE; }
@Test public void testSetItemTypes() throws Exception { cmd.setItemTypes(NodeTypes.Folder.NAME + "," + NodeTypes.Page.NAME); Rule rule = cmd.getRule(); assertTrue(rule.isAllowed(folder)); assertTrue(rule.isAllowed(page)); assertTrue(rule.isAllowed(resource)); assertTrue(rule.isAllowed(metadata)); assertFalse(rule.isAll...
RuleBasedCommand extends BaseRepositoryCommand { public void setRule(Rule rule) { this.rule = rule; } Rule getRule(); String getItemTypes(); void setItemTypes(String nodeTypes); void setRule(Rule rule); @Override void release(); static final String ATTRIBUTE_RULE; }
@Test public void testSetRule() throws Exception { Rule rule = new Rule(); rule.addAllowType(NodeTypes.Page.NAME); cmd.setRule(rule); rule = cmd.getRule(); assertTrue(rule.isAllowed(page)); assertFalse(rule.isAllowed(resource)); assertFalse(rule.isAllowed(metadata)); assertFalse(rule.isAllowed(folder)); assertFalse(rul...
DeleteCommand extends BaseRepositoryCommand { @Override public boolean execute(Context ctx) throws Exception { log.debug("Going to remove node [{}].", getPath()); String parentPath = StringUtils.substringBeforeLast(getPath(), "/"); String label = StringUtils.substringAfterLast(getPath(), "/"); Node parentNode = MgnlCon...
@Test public void testDeleteLeaveNode() throws Exception { cmd.setRepository(WEBSITE); cmd.setPath(secondLevel.getPath()); assertTrue(cmd.execute(ctx)); assertTrue(node.hasNode("first-level")); assertFalse(node.hasNode("first-level/second-level")); } @Test public void testDeleteNodeWithSubnodes() throws Exception { cmd...
MarkNodeAsDeletedCommand extends BaseRepositoryCommand { @Override public boolean execute(Context context) throws Exception { versionManager = Components.getComponent(VersionManager.class); final Node parentNode = getJCRNode(context); final Node node = parentNode.getNode((String) context.get(DELETED_NODE_PROP_NAME)); b...
@Test public void testUpdateAuthorIdAndModificationDateWhenMarkNodeAsDelete() throws Exception{ Calendar timeBeforeDelete = new GregorianCalendar(TimeZone.getDefault()); NodeTypes.LastModified.update(node, "user-before-delete", timeBeforeDelete); NodeTypes.LastModified.update(childNode, "user-before-delete", timeBefore...
RegistryMap { public synchronized V get(K key) { return map.get(key); } synchronized V get(K key); synchronized V getRequired(K key); synchronized void put(K key, V value); synchronized void put(V value); synchronized void remove(K key); synchronized void removeAndPutAll(Collection<K> toRemove, Map<K, V> toPut); synch...
@Test public void testReturnsNullWhenValueMissing() throws Exception { RegistryMap<String, String> map = new RegistryMap<String, String>(); assertNull(map.get("key")); }
RegistryMap { public synchronized V getRequired(K key) throws RegistrationException { V value = map.get(key); if (value == null) { throw new RegistrationException("Entry for [" + key + "] not found in registry, available entries are: " + (map.isEmpty() ? "<none>" : StringUtils.join(map.keySet(), ", "))); } return value...
@Test(expected = RegistrationException.class) public void testThrowsExceptionWhenRequiredAndMissing() throws Exception { RegistryMap<String, String> map = new RegistryMap<String, String>(); assertEquals("value", map.getRequired("key")); }
AuditLoggingManager { public void log(String action, String[] data) { StringBuilder message = new StringBuilder(); LogConfiguration trail = this.getLogConfiguration(action); if (trail == null) { applog.trace("Can't get log configuration"); } else { String separator = defaultSeparator; if (!StringUtils.isEmpty(trail.get...
@Test public void testNoErrorIsThrownInCaseOfMissingLogConfiguration() { AuditLoggingManager mgr = new AuditLoggingManager(); try { mgr.log("test", new String[]{"NPE?"}); } catch (Throwable t) { fail("Unexepcted Exception:" + t); } }
AuditLoggingUtil { @Deprecated public static void log(String action, String workspaceName, ItemType nodeType, String nodePath) { AuditLoggingUtil.log(action, new String[]{AuditLoggingUtil.getUser(), workspaceName, nodeType == null ? "" : nodeType.getSystemName(), nodePath}); } @Deprecated static void log(String action...
@Test public void testLogsLoginSuccesses() { final User user = createStrictMock(User.class); final HttpServletRequest request = createStrictMock(HttpServletRequest.class); final LoginResult loginResult = new LoginResult(LoginResult.STATUS_SUCCEEDED, MockUtil.createSubject(user)); expect(request.getParameter("mgnlUserId...
HierarchyBasedI18nContentSupport extends AbstractI18nContentSupport { @Override public NodeData getNodeData(Content node, String name) { return node.getNodeData(name); } @Override NodeData getNodeData(Content node, String name); }
@Override @Test public void testGetNodeDataEndlessLoop() throws Exception { HierarchyBasedI18nContentSupport defSupport = new HierarchyBasedI18nContentSupport(); defSupport.setEnabled(true); defSupport.setFallbackLocale(DEFAULT_LOCALE); defSupport.addLocale(new LocaleDefinition("de", "CH", true)); defSupport.addLocale(...
ExceptionUtil { public static <E extends Throwable> void unwrapIf(RuntimeException e, Class<E> unwrapIf) throws E { final Throwable wrapped = e.getCause(); if (unwrapIf != null && unwrapIf.isInstance(wrapped)) { throw (E) wrapped; } else if (wrapped != null && wrapped instanceof RuntimeException) { throw (RuntimeExcept...
@Test public void testUnwrapIfShouldThrowPassedExceptionIfItDoesNotMatchAndIsntARuntimeException() { final IOException originalException = new IOException("AIE"); final RuntimeException runtimeWrapping = new RuntimeException(originalException); try { ExceptionUtil.unwrapIf(runtimeWrapping, RepositoryException.class); f...
ExceptionUtil { @SuppressWarnings("unchecked") public static void rethrow(Throwable e, Class<? extends Throwable>... allowedExceptions) { if (RuntimeException.class.isInstance(e)) { throw (RuntimeException) e; } for (Class<? extends Throwable> allowedException : allowedExceptions) { if (allowedException.isInstance(e)) ...
@Test public void exampleOfAbuse() { try { ExceptionUtil.rethrow(new IOException(), IOException.class); fail("should have thrown an undeclared IOException"); } catch (Throwable e) { if (e.getClass().equals(IOException.class)) { } else { fail("should have thrown an undeclared IOException"); } } }
ExceptionUtil { public static String classNameToWords(Exception e) { return StringUtils.capitalize(StringUtils.removeEnd(e.getClass().getSimpleName(), "Exception").replaceAll("[A-Z]", " $0").toLowerCase().trim()); } static void unwrapIf(RuntimeException e, Class<E> unwrapIf); @SuppressWarnings("unchecked") static void...
@Test public void translatesSimpleExceptionNameProperly() { assertEquals("Path not found", ExceptionUtil.classNameToWords(new PathNotFoundException())); }
ExceptionUtil { public static String exceptionToWords(Exception e) { if (e.getMessage() != null) { return classNameToWords(e) + ": " + e.getMessage(); } else { return classNameToWords(e); } } static void unwrapIf(RuntimeException e, Class<E> unwrapIf); @SuppressWarnings("unchecked") static void rethrow(Throwable e, Cl...
@Test public void translatesSimpleExceptionWithMessage() { assertEquals("Path not found: /foo/bar", ExceptionUtil.exceptionToWords(new PathNotFoundException("/foo/bar"))); } @Test public void ignoresExceptionSuffixIfNotPresent() { assertEquals("Dummy problem: lol", ExceptionUtil.exceptionToWords(new DummyProblem("lol")...
ExceptionUtil { public static boolean wasCausedBy(Throwable e, Class<? extends Throwable> suspectedCause) { if (e != null && suspectedCause.isAssignableFrom(e.getClass())) { return true; } else if (e == null) { return false; } else { return wasCausedBy(e.getCause(), suspectedCause); } } static void unwrapIf(RuntimeExc...
@Test public void wasCausedByReturnsTrueIfGivenExceptionMatches() { assertTrue(wasCausedBy(new MgnlException(), MgnlException.class)); } @Test public void wasCausedByReturnsTrueIfCauseExceptionMatches() { assertTrue(wasCausedBy(new RuntimeException(new MgnlException()), MgnlException.class)); } @Test public void wasCau...
NodeDataUtil { public static Value createValue(String valueStr, int type) throws RepositoryException { HierarchyManager hm = MgnlContext.getSystemContext().getHierarchyManager(RepositoryConstants.CONFIG); ValueFactory valueFactory = hm.getWorkspace().getSession().getValueFactory(); return createValue(valueStr, type, va...
@Test public void testCreateValueWithDouble() throws Exception{ ValueFactory valueFactory = createNiceMock(ValueFactory.class); replay(valueFactory); double three = 3; Object obj = Double.valueOf(three); valueFactory.createValue(three); NodeDataUtil.createValue(obj, valueFactory); verify(valueFactory); } @Test public v...
NodeDataUtil { public static NodeData setValue(NodeData nodeData, Object valueObj) throws AccessDeniedException, RepositoryException{ if(valueObj == null){ nodeData.setValue(StringUtils.EMPTY); } else{ switch (PropertyUtil.getJCRPropertyType(valueObj)) { case PropertyType.STRING: nodeData.setValue((String)valueObj); br...
@Test public void testSetNodeDataWithDouble() throws Exception { NodeData data = new MockNodeData("test", 0); NodeDataUtil.setValue(data, Double.valueOf(3)); assertEquals(3.0, data.getDouble(), 0.0); } @Test public void testSetNodeDataWithFloat() throws Exception { NodeData data = new MockNodeData("test", 0); NodeDataU...
NodeUuidComparator implements Comparator<Content> { @Override public int compare(Content c1, Content c2) { final String s1 = c1.getUUID(); final String s2 = c2.getUUID(); return s1.compareTo(s2); } @Override int compare(Content c1, Content c2); }
@Test public void testBasic() { final MockContent a = new MockContent("a"); a.setUUID("a-uuid"); final MockContent b = new MockContent("b"); b.setUUID("b-uuid"); final MockContent otherA = new MockContent("other-a"); otherA.setUUID("a-uuid"); final NodeUuidComparator comparator = new NodeUuidComparator(); assertEquals(...
WebXmlUtil { public int checkFilterDispatchersConfiguration(String filterClass, List mandatoryDispatchers, List optionalDispatchers) { final Element filterEl = getFilterElement(filterClass); if (filterEl != null) { final String filterName = filterEl.getTextNormalize(); final String filterMappingXPathExpr = "/webxml:web...
@Test public void testFilterDispatcherChecksShouldNotFailWithCorrectConfiguration() { WebXmlUtil util = new WebXmlUtil(getClass().getResourceAsStream("web_filterok.xml")); assertEquals(1, util.checkFilterDispatchersConfiguration(MgnlMainFilter.class.getName(), MANDATORY_DISPATCHERS, OPTIONAL_DISPATCHERS)); } @Test publ...
WebXmlUtil { public boolean isFilterRegistered(String filterClass) { return getFilterElement(filterClass) != null; } WebXmlUtil(); WebXmlUtil(InputStream inputStream); boolean isServletOrMappingRegistered(String servletName); boolean isServletRegistered(String servletName); boolean isServletMappingRegistered(String se...
@Test public void testCanDetectFilterRegistration() { WebXmlUtil util = new WebXmlUtil(getClass().getResourceAsStream("web_filterwrongdispatchers.xml")); assertEquals(true, util.isFilterRegistered("webxmltest.OrderIsIrrelevant")); assertEquals(false, util.isFilterRegistered("nonregistered.BlehFilter")); }
ExtendingContentWrapper extends ContentWrapper { @Override public Content getContent(String name) throws RepositoryException { Content content; if (getWrappedContent().hasContent(name)) { content = getWrappedContent().getContent(name); } else if (extending && extendedContent.hasContent(name)) { content = extendedConten...
@Test public void testExtendsNonAbsolutelyAndNodeIsNotExisting() throws IOException, RepositoryException { HierarchyManager hm = MockUtil.createHierarchyManager("/superbase/nodeData1=org1\n" + "/superbase/uglyChild/nodeDataX=over1\n" + "/impl/node/extends=/superbase\n" + "/impl/node2/extends=../../superbase/uglyChild\n...
WorkspaceXmlUtil { public static List<String> getWorkspaceNames(String xPathExpression, String expectation) { final List<String> names = new ArrayList<String>(); final String dir = SystemProperty.getProperty(SystemProperty.MAGNOLIA_REPOSITORIES_HOME) + "/magnolia/workspaces/"; log.debug("Checking directory " + dir); fi...
@Test public void testWorkspaceNamesWithNonNullExpectation() { List<String> names = WorkspaceXmlUtil.getWorkspaceNames("/Workspace/SearchIndex/param[@name='textFilterClasses']/@value", ".*\\.jackrabbit\\.extractor\\..*"); assertEquals("Found incorrect amount of indexers", 1, names.size()); assertTrue(names.get(0).conta...
InheritanceContentWrapper extends ContentWrapper { @Override public NodeData getNodeData(String name) { try { if (getWrappedContent().hasNodeData(name)) { return getWrappedContent().getNodeData(name); } Content inherited = getContentSafely(findNextAnchor(), resolveInnerPath()); if(inherited != null){ return inherited.g...
@Test public void testRoot() throws Exception { setUpContent("testPropertyInheritance"); Content root = new InheritanceContentWrapper(hm.getRoot()); NodeData nd = root.getNodeData("whateverThatIsNotOnTheNodeItself"); assertTrue(nd instanceof NonExistingNodeData); } @Test public void testPropertyInheritance() throws Exc...
InheritanceContentWrapper extends ContentWrapper { @Override public Content getContent(String name) throws RepositoryException { Content inherited = getContentSafely(name); if(inherited == null){ throw new PathNotFoundException("Can't inherit a node [" + name + "] on node [" + getWrappedContent().getHandle() + "]"); } ...
@Test public void testNestedParagraphInheritance() throws Exception { setUpContent("testNestedParagraphInheritance"); Content page11 = getWrapped("/page1/page11"); Content page12 = getWrapped("/page1/page12"); Content containerPage11 = page11.getContent("container"); Content containerPage12 = page12.getContent("contain...
InheritanceContentWrapper extends ContentWrapper { @Override public boolean hasNodeData(String name) throws RepositoryException { try { if (getWrappedContent().hasNodeData(name)) { return getWrappedContent().hasNodeData(name); } Content inherited = getContentSafely(findNextAnchor(), resolveInnerPath()); if (inherited !...
@Test public void testHasPropertyInheritance() throws Exception { setUpContent("testPropertyInheritance"); Content page11 = getWrapped("/page1/page11"); Content page12 = getWrapped("/page1/page12"); assertTrue(page11.hasNodeData("nd")); assertTrue(page12.hasNodeData("nd")); } @Test public void testHasNestedPropertyInhe...
SystemContentWrapper extends LazyContentWrapper { @Override public HierarchyManager getHierarchyManager() { return LifeTimeJCRSessionUtil.getHierarchyManager(getRepository()); } SystemContentWrapper(String repository, String uuid); SystemContentWrapper(Content node); @Override HierarchyManager getHierarchyManager(); @...
@Test public void testClosedSessionResistance() throws Exception { HierarchyManager hm = MgnlContext.getInstance().getHierarchyManager("config"); assertNotSame(hm, LifeTimeJCRSessionUtil.getHierarchyManager("config")); hm.getRoot().createContent("bla", ItemType.CONTENT.getSystemName()).setNodeData("nodeData2", "boo"); ...
SearchReplace implements ContentUtil.Visitor { @Override public void visit(Content node) throws Exception { final Collection<NodeData> props = node.getNodeDataCollection(propertyNamePattern); for (NodeData prop : props) { if (prop.isExist()) { final String oldValue = prop.getString(); final StringBuffer newValue = new ...
@Test public void testCaseInsensitive() throws Exception { assertEquals("maGnolia is Great", prop("/top/text")); assertEquals("maGnolia is Great", prop("/top/chalala")); assertEquals("magnolia rules", prop("/top/other/text")); assertEquals("the rules of magnoliA", prop("/top/other2/text")); assertEquals("the rules of M...
LinkUtil { public static String addFingerprintToLink(String link, Calendar lastModified) { String fingerprintedLink = ""; if (lastModified == null) { return link; } String fingerprint = FINGERPRINT_FORMAT.format(lastModified.getTime()); int lastDot = link.lastIndexOf('.'); int lastSlash = link.lastIndexOf('/'); if (las...
@Test public void testAddFingerprintToLink() throws Exception { String link1 = LinkUtil.addFingerprintToLink(link, calendar1); assertEquals("server/path/filename.2000-02-01-01-01-01.png", link1); } @Test public void testAddFingerprintToLinkFundamentalAssertions() throws Exception { String link1 = LinkUtil.addFingerprin...
LinkUtil { public static String removeFingerprintAndExtensionFromLink(String originalPath) { String subPath = StringUtils.substringBeforeLast(originalPath, "."); String fingerPrint = StringUtils.substringAfterLast(subPath, "."); if (fingerPrint != null && fingerPrint.matches("\\d{4}-\\d{2}-\\d{2}-\\d{2}-\\d{2}-\\d{2}")...
@Test public void testRemoveFingerprintAndExtensionFromLink() throws Exception { String link1 = LinkUtil.removeFingerprintAndExtensionFromLink("server/path/filename.2000-02-01-01-01-01.png"); assertEquals("server/path/filename", link1); }
QueryUtil { public static NodeIterator search(QueryObjectModel model, String returnItemType) throws InvalidQueryException, RepositoryException{ return NodeUtil.filterDuplicates(NodeUtil.filterParentNodeType(model.execute().getNodes(), returnItemType)); } static Collection<Content> query(String repository, String state...
@Test public void testSimpleQuery() throws InvalidQueryException, RepositoryException{ String statement = "select * from [mgnl:page]"; NodeIterator result = QueryUtil.search("website", statement); Collection<Node> collection = NodeUtil.getCollectionFromNodeIterator(result); assertEquals(7, collection.size()); } @Test p...
QueryUtil { public static String buildQuery (String statement, String startPath){ Set<String> arguments = new HashSet<String>(Arrays.asList(StringUtils.splitByWholeSeparator(statement, ","))); Iterator<String> argIt = arguments.iterator(); String queryString = "select * from [nt:base] as t where ISDESCENDANTNODE(["+sta...
@Test public void testQueryBuild(){ assertEquals("select * from [nt:base] as t where ISDESCENDANTNODE([/site1]) AND contains(t.*, 'area') AND contains(t.*, 'component')", QueryUtil.buildQuery("component,area", "/site1")); }
RequestDispatchUtil { public static boolean dispatch(String targetUri, HttpServletRequest request, HttpServletResponse response) { if (targetUri == null) { return false; } if (targetUri.startsWith(REDIRECT_PREFIX)) { String redirectUrl = StringUtils.substringAfter(targetUri, REDIRECT_PREFIX); try { if (isInternal(redir...
@Test public void testDispatchWithNullURI() { final String targetUri = null; boolean result = RequestDispatchUtil.dispatch(targetUri, null, null); assertFalse(result); } @Test public void testDispatchRedirectInternal() throws Exception { final String contextPath = "contextPath"; final String targetUri = RequestDispatch...
ModuleConfigurationObservingManager { public void start() { for (String moduleName : moduleRegistry.getModuleNames()) { String path = "/modules/" + moduleName + "/" + pathWithinModule; observedPaths.add(path); } final EventListener eventListener = ObservationUtil.instanciateDeferredEventListener(new EventListener() { @...
@Test public void testObserving() throws RepositoryException, IOException, InterruptedException { final Session session = SessionTestUtil.createSession("testWorkspace", "/modules/foo/components/a\n" + "/modules/bar/components/b\n" + "/modules/zed\n" ); MockUtil.getSystemMockContext().addSession(RepositoryConstants.CONF...
ServletUtil { public static LinkedHashMap<String, String> initParametersToMap(ServletConfig config) { LinkedHashMap<String, String> initParameters = new LinkedHashMap<String, String>(); Enumeration parameterNames = config.getInitParameterNames(); while (parameterNames.hasMoreElements()) { String parameterName = (String...
@Test public void testServletInitParametersToMap() { LinkedHashMap<String, String> initParameters = new LinkedHashMap<String, String>(); initParameters.put("key1", "value1"); initParameters.put("key2", "value2"); initParameters.put("key3", "value3"); CustomServletConfig servletConfig = new CustomServletConfig("servlet"...
ServletUtil { public static <T extends ServletRequest> T getWrappedRequest(ServletRequest request, Class<T> clazz) { while (request != null) { if (clazz.isAssignableFrom(request.getClass())) { return (T) request; } request = (request instanceof ServletRequestWrapper) ? ((ServletRequestWrapper) request).getRequest() : n...
@Test public void testGetWrappedRequest() { MockHttpServletRequest mock = new MockHttpServletRequest(); HttpServletRequest request = new HttpServletRequestWrapper(mock) {}; assertNotNull(ServletUtil.getWrappedRequest(request, MockHttpServletRequest.class)); assertNull(ServletUtil.getWrappedRequest(mock, request.getClas...
ServletUtil { public static boolean isMultipart(HttpServletRequest request) { String contentType = request.getContentType(); return contentType != null && contentType.toLowerCase().startsWith("multipart/"); } static LinkedHashMap<String, String> initParametersToMap(ServletConfig config); static LinkedHashMap<String, S...
@Test public void testIsMultipart() { MockHttpServletRequest mock = new MockHttpServletRequest(); mock.setContentType("multipart/form-data"); assertTrue(ServletUtil.isMultipart(mock)); mock.setContentType("multipart/whatever"); assertTrue(ServletUtil.isMultipart(mock)); mock.setContentType("MULTIPART/form-data"); asser...
ServletUtil { public static boolean isForward(HttpServletRequest request) { return request.getAttribute(FORWARD_REQUEST_URI_ATTRIBUTE) != null && !isInclude(request); } static LinkedHashMap<String, String> initParametersToMap(ServletConfig config); static LinkedHashMap<String, String> initParametersToMap(FilterConfig ...
@Test public void testIsForward() { MockHttpServletRequest mock = new MockHttpServletRequest(); assertFalse(ServletUtil.isForward(mock)); mock.setAttribute(ServletUtil.FORWARD_REQUEST_URI_ATTRIBUTE, "/test.html"); assertTrue(ServletUtil.isForward(mock)); mock.setAttribute(ServletUtil.INCLUDE_REQUEST_URI_ATTRIBUTE, "/te...
ServletUtil { public static boolean isInclude(HttpServletRequest request) { return request.getAttribute(INCLUDE_REQUEST_URI_ATTRIBUTE) != null; } static LinkedHashMap<String, String> initParametersToMap(ServletConfig config); static LinkedHashMap<String, String> initParametersToMap(FilterConfig config); static T getWr...
@Test public void testIsInclude() { MockHttpServletRequest mock = new MockHttpServletRequest(); assertFalse(ServletUtil.isInclude(mock)); mock.setAttribute(ServletUtil.FORWARD_REQUEST_URI_ATTRIBUTE, "/test.html"); assertFalse(ServletUtil.isInclude(mock)); mock.setAttribute(ServletUtil.INCLUDE_REQUEST_URI_ATTRIBUTE, "/t...
ServletUtil { public static boolean isError(HttpServletRequest request) { return request.getAttribute(ERROR_REQUEST_STATUS_CODE_ATTRIBUTE) != null; } static LinkedHashMap<String, String> initParametersToMap(ServletConfig config); static LinkedHashMap<String, String> initParametersToMap(FilterConfig config); static T g...
@Test public void testIsError() { MockHttpServletRequest mock = new MockHttpServletRequest(); assertFalse(ServletUtil.isError(mock)); assertFalse(ServletUtil.isForward(mock)); assertFalse(ServletUtil.isInclude(mock)); mock.setAttribute(ServletUtil.ERROR_REQUEST_STATUS_CODE_ATTRIBUTE, 500); assertTrue(ServletUtil.isErro...
ServletUtil { public static DispatcherType getDispatcherType(HttpServletRequest request) { if (request.getAttribute(INCLUDE_REQUEST_URI_ATTRIBUTE) != null) { return DispatcherType.INCLUDE; } if (request.getAttribute(FORWARD_REQUEST_URI_ATTRIBUTE) != null) { return DispatcherType.FORWARD; } if (request.getAttribute(ERRO...
@Test public void testGetDispatcherType() { MockHttpServletRequest mock = new MockHttpServletRequest(); assertEquals(DispatcherType.REQUEST, ServletUtil.getDispatcherType(mock)); mock.setAttribute(ServletUtil.FORWARD_REQUEST_URI_ATTRIBUTE, "/test.html"); assertEquals(DispatcherType.FORWARD, ServletUtil.getDispatcherTyp...
ServletUtil { public static String getOriginalRequestURI(HttpServletRequest request) { if (request.getAttribute(FORWARD_REQUEST_URI_ATTRIBUTE) != null) { return (String) request.getAttribute(FORWARD_REQUEST_URI_ATTRIBUTE); } return request.getRequestURI(); } static LinkedHashMap<String, String> initParametersToMap(Ser...
@Test public void testGetOriginalRequestUri() { MockHttpServletRequest mock = new MockHttpServletRequest(); mock.setRequestURI("/some/path/and/some.file"); assertEquals("/some/path/and/some.file", ServletUtil.getOriginalRequestURI(mock)); mock.setAttribute(ServletUtil.FORWARD_REQUEST_URI_ATTRIBUTE, mock.getRequestURI()...
TemplatingFunctions { public ContentMap page(ContentMap content) throws RepositoryException { return content == null ? null : asContentMap(page(content.getJCRNode())); } @Inject TemplatingFunctions(Provider<AggregationState> aggregationStateProvider); Node asJCRNode(ContentMap contentMap); ContentMap asContentMap(Node...
@Test public void testPageFromRootShouldBeNull() throws RepositoryException { Node resultNode = functions.page(root); assertNull(resultNode); } @Test public void testPageHavingNoParentPageShouldBeNull() throws RepositoryException { Node componentWithoutPage = root.addNode("onlyComponent", NodeTypes.Component.NAME); Nod...
ServletUtil { public static String getOriginalRequestURLIncludingQueryString(HttpServletRequest request) { if (request.getAttribute(FORWARD_REQUEST_URI_ATTRIBUTE) != null) { StringBuilder builder = new StringBuilder(); String scheme = request.getScheme(); builder.append(scheme).append(": int port = request.getServerPor...
@Test public void testGetOriginalRequestUrlIncludingQueryString() { MockHttpServletRequest mock = new MockHttpServletRequest(); mock.setRequestURL("http: mock.setRequestURI("/foo/bar.html"); mock.setQueryString("a=5&b=6"); assertEquals("http: mock.setAttribute(ServletUtil.FORWARD_REQUEST_URI_ATTRIBUTE, mock.getRequestU...
DelayedExecutor { public synchronized void trigger() { long now = System.currentTimeMillis(); log.debug("execution triggered"); if (timestamp == 0) { timestamp = now; } if (taskId != null && (timestamp + maxDelay >= now)) { log.debug("execution canceled"); ClockDaemon.cancel(taskId); } taskId = timer.executeAfterDelay(...
@Test public void testDelayedExecution() throws InterruptedException{ TestRunnable runnable = new TestRunnable(); DelayedExecutor executor = new DelayedExecutor(runnable, 100, 500); executor.trigger(); Thread.sleep(50); assertEquals(false, runnable.executed); Thread.sleep(70); assertEquals(true, runnable.executed); } @...
LazyContentWrapper extends ContentWrapper implements Serializable { @Override public HierarchyManager getHierarchyManager() { return MgnlContext.getSystemContext().getHierarchyManager(getRepository()); } LazyContentWrapper(String repository, String uuid); LazyContentWrapper(Content node); @Override synchronized Conten...
@Test public void testClosedSessionResistance() throws Exception { HierarchyManager hm = MgnlContext.getInstance().getHierarchyManager("config"); assertNotSame(hm, LifeTimeJCRSessionUtil.getHierarchyManager("config")); hm.getRoot().createContent("bla", ItemType.CONTENT.getSystemName()).setNodeData("nodeData2", "boo"); ...
Rule implements Serializable { @Override public String toString() { StringBuffer buffer = new StringBuffer(); Iterator<String> typeIterator = allowedTypes.iterator(); while (typeIterator.hasNext()) { buffer.append(typeIterator.next()); buffer.append(","); } return buffer.toString(); } Rule(); Rule(String[] allowedType...
@Test public void testRuleStringConstructor() { String allowedTypes = "mgnl:resource,mgnl:contentNode,mgnl:metaData"; Rule rule = null; rule = new Rule(allowedTypes, ","); Assert.assertEquals(allowedTypes+",", rule.toString()); }
Rule implements Serializable { public boolean isAllowed(String nodeType) { boolean allowed = this.allowedTypes.contains(nodeType); if (this.reverse) { return !allowed; } return allowed; } Rule(); Rule(String[] allowedTypes); Rule(String allowedTypes, String separator); void setAllowedTypes(String[] types); void addAl...
@Test public void testIsAllowedNode() throws RepositoryException { Session session = MgnlContext.getJCRSession(RepositoryConstants.WEBSITE); Node node = session.getRootNode().addNode( "page", NodeTypes.Area.NAME); String allowedTypes = "mgnl:contentNode"; Rule rule = new Rule(allowedTypes, ","); boolean allowed = rule....
ClasspathResourcesUtil { protected static File sanitizeToFile(URL url) { try { String fileUrl = url.getFile(); fileUrl = URLDecoder.decode(fileUrl, "UTF-8"); fileUrl = StringUtils.removeStart(fileUrl, "file:"); fileUrl = StringUtils.removeEnd(fileUrl, "!/"); return new File(fileUrl); } catch (UnsupportedEncodingExcepti...
@Test public void testOhWindoes() throws MalformedURLException { URL u1 = new URL("file:/C:/tomcat 5.5.20/webapps/magnoliaAuthor/WEB-INF/lib/foo-1.2.3.jar"); URL u2 = new URL("file:/C:/tomcat%205.5.20/webapps/magnoliaAuthor/WEB-INF/lib/foo-1.2.3.jar"); File sanitFile1 = ClasspathResourcesUtil.sanitizeToFile(u1); File s...
ContentUtil { public static void visit(Content node, Visitor visitor) throws Exception{ visit(node, visitor, EXCLUDE_META_DATA_CONTENT_FILTER); } static Content getContent(String repository, String path); static Content getContentByUUID(String repository, String uuid); static Content getContent(Content node, String na...
@Test public void testVisitShouldPassFilterAlong() throws Exception { final ItemType foo = new ItemType("foo"); final ItemType bar = new ItemType("bar"); final MockContent root = new MockContent(MockNode.ROOT_NODE_NAME, foo); final MockContent child1 = new MockContent("child1", foo); root.addContent(child1); final Mock...
ContentUtil { public static void orderAfter(Content nodeToMove, String targetNodeName) throws RepositoryException{ Content parent = nodeToMove.getParent(); Boolean readyToMove = false; Collection<Content> children = new ArrayList<Content>(ContentUtil.getAllChildren(parent)); for (Content child : children) { if(readyToM...
@Test public void testOrderAfter() throws RepositoryException, IOException{ MockHierarchyManager hm = MockUtil.createHierarchyManager( "/node/a\n" + "/node/b\n" + "/node/c\n"); Content node = hm.getContent("/node"); Content a = node.getContent("a"); ContentUtil.orderAfter(a, "b"); Collection<Content> result = node.getC...
ContentUtil { public static Content asContent(Node content) { if(content == null) { return null; } return new DefaultContent(content); } static Content getContent(String repository, String path); static Content getContentByUUID(String repository, String uuid); static Content getContent(Content node, String name); stat...
@Test public void testAsContent() throws Exception{ MockSession session = SessionTestUtil.createSession("testWorkspace","/foo/bar/sub1.@uuid=1"); Node node = session.getNode("/foo/bar/sub1"); Content content = ContentUtil.asContent(node); assertEquals(node, content.getJCRNode()); assertTrue(content instanceof DefaultCo...
DateUtil { public static String format(Date date, String formatPattern) { return format(date, formatPattern, Locale.getDefault()); } private DateUtil(); static String format(Date date, String formatPattern); static String format(Date date, String formatPattern, Locale locale); static String formatDateTime(Object val);...
@Test public void testCustomFormatShouldUseGivenLocale() { assertEquals("Sunday, 6. July 2008", DateUtil.format(getTestDate(), "EEEE, d. MMMM yyyy", new Locale("en"))); assertEquals("Sonntag, 6. Juli 2008", DateUtil.format(getTestDate(), "EEEE, d. MMMM yyyy", new Locale("de"))); assertEquals("sunnuntai, 6. hein\u00e4ku...
ClassUtil { public static boolean isSubClass(Class<?> subClass, Class<?> parentClass) { return parentClass.isAssignableFrom(subClass); } private ClassUtil(); static Class classForName(String className); static Object newInstance(String className); static boolean isSubClass(Class<?> subClass, Class<?> parentClass); }
@Test public void testIsSubClass() throws Exception { assertTrue(ClassUtil.isSubClass(Bar.class, Foo.class)); assertTrue(ClassUtil.isSubClass(Foo.class, Object.class)); assertTrue(ClassUtil.isSubClass(Bar.class, Object.class)); }
ObservationUtil { public static void registerChangeListener(String workspace, String observationPath, EventListener listener) { registerChangeListener(workspace, observationPath, true, listener); } static void dispose(String workspace); static void registerChangeListener(String workspace, String observationPath, Event...
@Test public void testFailRegisterWhenSessionInvalid() throws Exception { setupMockSession(false); try { ObservationUtil.registerChangeListener("some-repo", "/parent", new EventListener() { @Override public void onEvent(EventIterator events) { } }); fail("Expected exception not thrown."); } catch (IllegalStateException...
ObservationUtil { public static void unregisterChangeListener(String workspace, EventListener listener) { try { ObservationManager om = getObservationManager(workspace); if (om == null) { return; } om.removeEventListener(listener); } catch (RepositoryException e) { log.error("Unable to remove event listener [" + listen...
@Test public void testDontFailUnregisterWhenSessionInvalid() throws Exception { MockSession session = setupMockSession(false); ObservationManager observationManager = setupMockObservationManager(session); EventListener listener = new EventListener() { @Override public void onEvent(EventIterator events) { } }; Observati...
UnicodeNormalizer { public static String[] normalizeNFC(String[] values) { if (values == null) { return null; } for (int i = 0; i < values.length; i++) { values[i] = normalizeNFC(values[i]); } return values; } static String[] normalizeNFC(String[] values); static String normalizeNFC(String in); }
@Test public void testAsciiStringsShouldPassThroughWithAutoDetect() { assertEquals("hello", UnicodeNormalizer.normalizeNFC("hello")); } @Test public void testNFCStringIsStillEqualsAfterNormalizeCallWithAutoDetect() { assertEquals(NFC, UnicodeNormalizer.normalizeNFC(NFC)); } @Test public void testNormalizingNFDStringMak...
StringLengthComparator implements Comparator<String> { @Override public int compare(String name1, String name2) { return name1.length() - name2.length(); } @Override int compare(String name1, String name2); }
@Test public void testBasic() { assertEquals(0, new StringLengthComparator().compare("abc", "www")); assertTrue(new StringLengthComparator().compare("ac", "wwxxxw") < 0); assertTrue(new StringLengthComparator().compare("awwwc", "ww") > 0); }
SimpleUrlPattern implements UrlPattern { @Override public boolean match(String str) { return this.pattern.matcher(str).matches(); } SimpleUrlPattern(); SimpleUrlPattern(String string); static String getEncodedString(String str); @Override boolean match(String str); @Override int getLength(); @Override String getPatter...
@Test public void testDotDoPattern() { final SimpleUrlPattern sup = new SimpleUrlPattern("*.do"); assertFalse(sup.match("/.resources/enterprise-css/registration.css")); } @Test public void testNoWildcardsMatch() { assertTrue(new SimpleUrlPattern("/test/url.html").match("/test/url.html")); } @Test public void testNoWild...
PathUtil { public static String createPath(String path, String label) { String res; if (StringUtils.isEmpty(path) || (path.equals("/"))) { res = label; } else { res = path + "/" + label; } return addLeadingSlash(res); } static String createPath(String path, String label); static String addLeadingSlash(String path); st...
@Test public void testCreatePath() { assertEquals("/foo/bar", PathUtil.createPath("/foo", "bar")); assertEquals("/bar", PathUtil.createPath("/", "bar")); assertEquals("/bar", PathUtil.createPath("", "bar")); assertEquals("/bar", PathUtil.createPath(null, "bar")); assertEquals("/foo assertEquals("/foo/bar/zed", PathUtil...
PathUtil { public static String addLeadingSlash(String path) { if (!path.startsWith("/")) { return "/" + path; } return path; } static String createPath(String path, String label); static String addLeadingSlash(String path); static String getFolder(String path); static String getFileName(String path); static String ge...
@Test public void testAddLeadingSlash() { assertEquals("/", PathUtil.addLeadingSlash("/")); assertEquals("/", PathUtil.addLeadingSlash("")); assertEquals("/foo", PathUtil.addLeadingSlash("foo")); assertEquals("/foo", PathUtil.addLeadingSlash("/foo")); } @Test(expected = NullPointerException.class) public void testAddLe...
PathUtil { public static String getFolder(String path) { String res; res = StringUtils.substringBeforeLast(path, "/"); if (StringUtils.isEmpty(res)) { return "/"; } return res; } static String createPath(String path, String label); static String addLeadingSlash(String path); static String getFolder(String path); stati...
@Test public void testGetFolder() { assertEquals("/", PathUtil.getFolder("")); assertEquals("/", PathUtil.getFolder("/")); assertEquals("/", PathUtil.getFolder(null)); assertEquals("/foo", PathUtil.getFolder("/foo/bar")); assertEquals("foo", PathUtil.getFolder("foo/bar")); assertEquals("foobar", PathUtil.getFolder("foo...
PathUtil { public static String getFileName(String path) { if (path.indexOf("/") >= 0) { return StringUtils.substringAfterLast(path, "/"); } return path; } static String createPath(String path, String label); static String addLeadingSlash(String path); static String getFolder(String path); static String getFileName(St...
@Test public void testGetFileName() { assertEquals("bar", PathUtil.getFileName("/foo/bar")); assertEquals("bar", PathUtil.getFileName("foo/bar")); assertEquals("foo", PathUtil.getFileName("/foo")); assertEquals("", PathUtil.getFileName("foo/")); assertEquals("", PathUtil.getFileName("/foo/bar/")); assertEquals("", Path...
PathUtil { public static String getExtension(String path) { if (path == null) { return null; } return StringUtils.substringAfterLast(getFileName(path), "."); } static String createPath(String path, String label); static String addLeadingSlash(String path); static String getFolder(String path); static String getFileNam...
@Test public void testGetExtension() { assertEquals("html", PathUtil.getExtension("index.html")); assertEquals("", PathUtil.getExtension("index")); assertEquals("html", PathUtil.getExtension("/home/index.html")); assertEquals("html", PathUtil.getExtension("home/index.html")); assertEquals("", PathUtil.getExtension(""))...
PathUtil { public static String stripExtension(String path) { return StringUtils.substringBeforeLast(path, "."); } static String createPath(String path, String label); static String addLeadingSlash(String path); static String getFolder(String path); static String getFileName(String path); static String getExtension(St...
@Test public void testStripExtension() { assertEquals("index", PathUtil.stripExtension("index.html")); assertEquals("index", PathUtil.stripExtension("index")); assertEquals("/home/index", PathUtil.stripExtension("/home/index.html")); assertEquals("home/index", PathUtil.stripExtension("home/index.html")); assertEquals("...
TextFileUtil { public static List<String> getLines(String fileName) { final List<String> names = new ArrayList<String>(); BufferedReader jaasConfig = null; try { final File file = new File(fileName); if (!file.exists()) { throw new FileNotFoundException(fileName); } jaasConfig = new BufferedReader(new FileReader(fileNa...
@Test public void testGetLines() { final List<String> result = TextFileUtil.getLines("src/test/resources/config/current-jaas.config"); assertEquals(17, result.size()); } @Test public void testGetLinesWhenFileIsNotExisiting() { try { TextFileUtil.getLines("no/such/file.around"); fail("Should have thrown an exception!");...
TextFileUtil { public static List<String> getTrimmedLinesMatching(String fileName, String regExp) { final List<String> lines = getLines(fileName); final List<String> matchingLines = new ArrayList<String>(); String currentLine = null; for (Iterator<String> iterator = lines.iterator(); iterator.hasNext();) { currentLine ...
@Test public void testGetTrimmedLinesMatching() { final List<String> result = TextFileUtil.getTrimmedLinesMatching("src/test/resources/config/outdated-jaas.config", "^Jackrabbit.*"); assertEquals(1, result.size()); } @Test public void testGetTrimmedLinesMatchingWhenExpressionIsNotContained() { final List<String> result...
BooleanUtil { public static boolean toBoolean(String s, boolean defaultValue) { final Boolean b = BooleanUtils.toBooleanObject(s); return b == null ? defaultValue : b.booleanValue(); } static boolean toBoolean(String s, boolean defaultValue); }
@Test public void testToBooleanKnowsItsBasicEnglishVocabulary() { assertEquals(true, toBoolean("true", true)); assertEquals(true, toBoolean("true", false)); assertEquals(false, toBoolean("false", true)); assertEquals(false, toBoolean("false", false)); assertEquals(true, toBoolean("on", true)); assertEquals(true, toBool...
NodePathComparator implements Comparator<Content> { @Override public int compare(Content c1, Content c2) { final String s1 = c1.getHandle(); final String s2 = c2.getHandle(); return s1.compareTo(s2); } @Override int compare(Content c1, Content c2); }
@Test public void testBasic() { final MockContent a = new MockContent("a"); final MockContent b = new MockContent("b"); final MockContent otherB = new MockContent("b"); final MockContent c = new MockContent("c"); final MockContent d = new MockContent("d"); a.addContent(b); a.addContent(otherB); b.addContent(c); a.addCo...
MgnlGroup implements Group { @Override public Collection<String> getRoles() { return Collections.unmodifiableCollection(this.roles); } MgnlGroup(String id, String groupName, Collection<String> subgroupNames, Collection<String> roleNames); @Override String getName(); @Override void addRole(String roleName); @Override vo...
@Test public void testGetRoles() throws AccessDeniedException { final Collection rolesA = gman.getGroup("groupA").getRoles(); assertEquals(2, rolesA.size()); assertTrue(rolesA.contains("roleX")); assertTrue(rolesA.contains("roleY")); final Collection rolesC = gman.getGroup("groupC").getRoles(); assertEquals(0, rolesC.s...
MgnlGroup implements Group { @Override public Collection<String> getGroups() { return this.groups; } MgnlGroup(String id, String groupName, Collection<String> subgroupNames, Collection<String> roleNames); @Override String getName(); @Override void addRole(String roleName); @Override void addGroup(String groupName); @Ov...
@Test public void testGetGroupsReturnsDirectGroups() throws AccessDeniedException { final Collection groupsA = gman.getGroup("groupA").getGroups(); assertEquals(1, groupsA.size()); assertTrue(groupsA.contains("groupC")); final Collection groupsD = gman.getGroup("groupD").getGroups(); assertEquals(0, groupsD.size()); } ...
MgnlGroup implements Group { @Override public Collection<String> getAllGroups() { throw new UnsupportedOperationException("Use manager to modify this group"); } MgnlGroup(String id, String groupName, Collection<String> subgroupNames, Collection<String> roleNames); @Override String getName(); @Override void addRole(Stri...
@Test public void testGetAllGroupsFromOneConcreteGroup(){ final Collection<String> groups= gman.getAllGroups("groupE"); assertEquals(4, groups.size()); assertTrue(groups.contains("groupA")); assertTrue(groups.contains("groupC")); assertTrue(groups.contains("groupD")); assertTrue(groups.contains("groupF")); final Collec...
ContentSecurityFilter extends BaseSecurityFilter { @Override public boolean isAllowed(HttpServletRequest request, HttpServletResponse response) throws IOException { final String repositoryName = MgnlContext.getAggregationState().getRepository(); final String handle = MgnlContext.getAggregationState().getHandle(); final...
@Test public void testIsAllowedForAnonymous() throws Exception { when(MgnlContext.getUser().getName()).thenReturn(UserManager.ANONYMOUS_USER); when(request.getMethod()).thenReturn("GET"); final ContentSecurityFilter filter = new ContentSecurityFilter(); final boolean result = filter.isAllowed(request, response); assert...
URISecurityFilter extends BaseSecurityFilter { @Override public boolean isAllowed(HttpServletRequest request, HttpServletResponse response) throws IOException { final IPSecurityManager ipSecurityManager = IPSecurityManager.Factory.getInstance(); if (!ipSecurityManager.isAllowed(request)) { response.setStatus(HttpServle...
@Test public void testIsAllowedForAnonymous() throws Exception { when(MgnlContext.getUser().getName()).thenReturn(UserManager.ANONYMOUS_USER); when(request.getMethod()).thenReturn("GET"); final URISecurityFilter filter = new URISecurityFilter(); final boolean result = filter.isAllowed(request, response); assertEquals(f...
PermissionUtil { static long convertPermissions(String newPermissions) { String[] perms = newPermissions.split(", "); long oldPerms = 0; for (String perm : perms) { if (Session.ACTION_ADD_NODE.equals(perm)) { oldPerms += Permission.WRITE; } else if (Session.ACTION_READ.equals(perm)) { oldPerms += Permission.READ; } els...
@Test public void testConvertPermissions() { assertEquals(Session.ACTION_READ, PermissionUtil.convertPermissions(Permission.READ)); assertEquals("add_node,read,set_property", PermissionUtil.convertPermissions(Permission.WRITE)); assertEquals(Session.ACTION_REMOVE, PermissionUtil.convertPermissions(Permission.REMOVE)); ...
PermissionUtil { public static boolean isGranted(Node node, long requiredPermissions) throws RepositoryException { AccessManager ami = MgnlContext.getAccessManager(node.getSession().getWorkspace().getName()); return ami.isGranted(node.getPath(), requiredPermissions); } static AccessManager getAccessManager(String work...
@Test(expected = IllegalArgumentException.class) public void testIsGrantedForEmptyPermissionString() { PermissionUtil.isGranted((Session) null, "ignored", ""); }
MgnlUser extends AbstractUser implements User, Serializable { @Override public Collection<String> getGroups() { log.debug("getGroups()"); return groups; } MgnlUser(String name, String realm, Collection<String> groups, Collection<String> roles, Map<String, String> properties); MgnlUser(String name, String realm, Collec...
@Test public void testGetGroupsReturnsOnlyDirectGroups() { final Collection<String> g = uman.getUser("julien").getGroups(); assertEquals(1, g.size()); assertEquals("groupC", g.iterator().next()); } @Test public void testGetGroupsReturnsDirectGroupsWithoutDuplicates() { final Collection<String> groups = uman.getUser("ge...
MgnlUser extends AbstractUser implements User, Serializable { @Override public Collection<String> getAllGroups() { log.debug("get groups for {}", getName()); final Set<String> allGroups = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER); final Collection<String> groups = getGroups(); GroupManager man = SecuritySuppor...
@Test public void testGetAllGroupsReturnsDirectAndInheritedGroups() { final Collection<String> groups = uman.getUser("georges").getAllGroups(); assertEquals(4, groups.size()); assertTrue(groups.contains("groupA")); assertTrue(groups.contains("groupB")); assertTrue(groups.contains("groupC")); assertTrue(groups.contains(...
MgnlUser extends AbstractUser implements User, Serializable { @Override public Collection<String> getRoles() { log.debug("getRoles()"); return roles; } MgnlUser(String name, String realm, Collection<String> groups, Collection<String> roles, Map<String, String> properties); MgnlUser(String name, String realm, Collectio...
@Test public void testGetRolesReturnsDirectRoles() { final Collection<String> roles = uman.getUser("georges").getRoles(); assertEquals(3, roles.size()); assertTrue(roles.contains("roleV")); assertTrue(roles.contains("roleW")); assertTrue(roles.contains("roleX")); } @Test public void testGetRolesReturnsDirectRolesWithou...
MgnlUser extends AbstractUser implements User, Serializable { @Override public Collection<String> getAllRoles() { log.debug("get roles for {}", getName()); final Set<String> allRoles = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER); final Collection<String> roles = getRoles(); allRoles.addAll(roles); Collection<Str...
@Test public void testGetAllRolesReturnsDirectAndInheritedRoles() throws AccessDeniedException { final Collection<String> rolesG = uman.getUser("georges").getAllRoles(); assertEquals(5, rolesG.size()); assertTrue(rolesG.contains("roleV")); assertTrue(rolesG.contains("roleW")); assertTrue(rolesG.contains("roleX")); asse...
MgnlUser extends AbstractUser implements User, Serializable { @Override public boolean inGroup(String groupName) { log.debug("inGroup({})", groupName); return this.hasAny(groupName, NODE_GROUPS); } MgnlUser(String name, String realm, Collection<String> groups, Collection<String> roles, Map<String, String> properties); ...
@Test public void testInGroup(){ User georges = uman.getUser("georges"); assertTrue(georges.inGroup("groupB")); assertFalse(georges.inGroup("groupE")); assertFalse(georges.inGroup("notExistingGroup")); User julien = uman.getUser("julien"); assertTrue(julien.inGroup("groupC")); assertFalse(julien.inGroup("groupA")); }
PrincipalUtil { public static <T extends Principal> T findPrincipal(Subject subject, Class<T> clazz) { return findPrincipal(subject.getPrincipals(), clazz, null); } static Subject createSubject(User user); static T findPrincipal(Subject subject, Class<T> clazz); static ACL findAccessControlList(Iterable<Principal> pri...
@Test public void testFindPrincipal() throws Exception { Subject subject = new Subject(); User user = mock(User.class); subject.getPrincipals().add(user); assertSame(user, PrincipalUtil.findPrincipal(subject, User.class)); } @Test public void testFindPrincipalInCollection() throws Exception { Subject subject = new Subj...
PrincipalUtil { public static ACL findAccessControlList(Iterable<Principal> principals, String name) { return findPrincipal(principals, ACL.class, name); } static Subject createSubject(User user); static T findPrincipal(Subject subject, Class<T> clazz); static ACL findAccessControlList(Iterable<Principal> principals, ...
@Test public void testFindACLByName() throws Exception { Subject subject = new Subject(); PrincipalCollectionImpl collection = new PrincipalCollectionImpl(); ACLImpl acl = new ACLImpl("website", new ArrayList<Permission>()); collection.add(acl); subject.getPrincipals().add(collection); assertSame(acl, PrincipalUtil.fin...
PrincipalUtil { public static <T extends Principal> T removePrincipal(Iterable<Principal> principals, Class<T> clazz) { return removePrincipal(principals, clazz, null); } static Subject createSubject(User user); static T findPrincipal(Subject subject, Class<T> clazz); static ACL findAccessControlList(Iterable<Principa...
@Test public void testRemovePrincipal() throws Exception { Subject subject = new Subject(); User user = mock(User.class); subject.getPrincipals().add(user); assertSame(user, PrincipalUtil.removePrincipal(subject.getPrincipals(), User.class)); assertTrue(subject.getPrincipals().isEmpty()); } @Test public void testRemove...
HierarchicalUserManager extends MgnlUserManager { protected String getParentPath(String name) { final String lcName = name.toLowerCase(); if (lcName.length() < 3) { return "/" + getRealmName(); } return "/" + getRealmName() + "/" + lcName.charAt(0) + "/" + StringUtils.left(lcName, 2); } }
@Test public void testParentPathIsRealmIfNameShorterThan3Chars() { assertEquals("/public", hm.getParentPath("ab")); } @Test public void testParentPathShouldReflectFirstLettersOfNameAndIncludeRealmName() { assertEquals("/public/c/ca", hm.getParentPath("casimir")); } @Test public void testParentPathShouldBeLowercased() {...
MgnlUserManager extends RepositoryBackedSecurityManager implements UserManager { @Override public User createUser(final String name, final String pw) { return this.createUser(null, name, pw); } MgnlUserManager(); @Override void setMaxFailedLoginAttempts(int maxFailedLoginAttempts); @Override int getMaxFailedLoginAttemp...
@Test public void testUsernameIsValidatedUponCreation() { final String justCheckingIfValidateUsernameIsCalledMessage = "Yes! I wanted this method to be called !"; final MgnlUserManager hm = new MgnlUserManager() { @Override protected void validateUsername(String name) { throw new IllegalArgumentException(justCheckingIf...
MgnlUserManager extends RepositoryBackedSecurityManager implements UserManager { protected void validateUsername(String name) { if (StringUtils.isBlank(name)) { throw new IllegalArgumentException(name + " is not a valid username."); } User user; if (isAllowCrossRealmDuplicateNames()) { user = this.getUser(name); } else...
@Test public void testUsernameCantBeNull() { try { new MgnlUserManager().validateUsername(null); fail("should have failed"); } catch (IllegalArgumentException e) { assertEquals("null is not a valid username.", e.getMessage()); } } @Test public void testUsernameCantBeEmpty() { try { new MgnlUserManager().validateUsernam...
MgnlUserManager extends RepositoryBackedSecurityManager implements UserManager { @Override protected Node findPrincipalNode(String name, Session session) throws RepositoryException { String realmName = getRealmName(); final String where; if (Realm.REALM_ALL.getName().equals(realmName)) { where = "where name() = '" + na...
@Test public void testFindPrincipalNode() throws RepositoryException { final Session session = mock(Session.class); final Workspace workspace = mock(Workspace.class); final QueryManager qm = mock(QueryManager.class); final Query query = mock(Query.class); final QueryResult result = mock(QueryResult.class); final NodeIt...
MgnlUserManager extends RepositoryBackedSecurityManager implements UserManager { @Override public User setProperty(final User user, final String propertyName, final Value propertyValue) { return MgnlContext.doInSystemContext(new SilentSessionOp<User>(getRepositoryName()) { @Override public User doExec(Session session) ...
@Test public void testSetProperty() throws Exception { final SystemContext ctx = mock(SystemContext.class); final MgnlUser user = mock(MgnlUser.class); final String path = "users"; when(user.getPath()).thenReturn(path); final String propName = "prop"; final String propValue = "value"; final MgnlUserManager um = new Mgn...
SecurityUtil { public static String getPublicKey() { ActivationManager aman = Components.getComponentProvider().getComponent(ActivationManager.class); return aman.getPublicKey(); } static boolean isAnonymous(); static boolean isAuthenticated(); static String decrypt(String pass); static String decrypt(String message, ...
@Test public void testCrypt() throws Exception { String path = "src/test/resources/testkeypair.properties"; SystemProperty.setProperty("magnolia.author.key.location", path); ActivationManager actMan = mock(ActivationManager.class); ComponentsTestUtil.setInstance(ActivationManager.class, actMan); Properties p = new Prop...
SecurityUtil { public static MgnlKeyPair generateKeyPair(int keyLength) throws NoSuchAlgorithmException { KeyPairGenerator kgen = KeyPairGenerator.getInstance(ALGORITHM); kgen.initialize(keyLength); KeyPair key = kgen.genKeyPair(); return new MgnlKeyPair(byteArrayToHex(key.getPrivate().getEncoded()), byteArrayToHex(key...
@Test public void testBCProvider() throws Exception { SecurityUtil.generateKeyPair(1024); Provider[] providers = Security.getProviders(); boolean found = false; for (Provider p : providers) { if ("BC".equals(p.getName())) { found = true; break; } } assertTrue(found); }
SecurityUtil { public static String stripPasswordFromCacheLog(String log){ String value = stripParameterFromCacheLog(log, "mgnlUserPSWD"); value = stripParameterFromCacheLog(value, "passwordConfirmation"); value = stripParameterFromCacheLog(value, "password"); return value; } static boolean isAnonymous(); static boole...
@Test public void testPasswordRemovingMethodFromCache(){ String log = "The following URL took longer than 10 seconds (18) to render. This might cause timout exceptions on other requests to the same URI. [url=http: assertEquals(SecurityUtil.stripPasswordFromCacheLog(log), "The following URL took longer than 10 seconds (...
SecurityUtil { public static String stripPasswordFromUrl(String url){ if(StringUtils.isBlank(url)){ return null; } String value = null; value = StringUtils.substringBefore(url, "mgnlUserPSWD"); value = value + StringUtils.substringAfter(StringUtils.substringAfter(url, "mgnlUserPSWD"), "&"); return StringUtils.removeEnd...
@Test public void testPasswordRemovingMethodFromURL(){ String url = "http: String url2 = "http: assertEquals(SecurityUtil.stripPasswordFromUrl(url), "http: assertEquals(SecurityUtil.stripPasswordFromUrl(url2), "http: }
DelegatingUserManager implements UserManager { @Override public User getUser(final String name) throws UnsupportedOperationException { return delegateUntilSupportedAndNotNull(new Op<User>() { @Override public User delegate(UserManager um) { return um.getUser(name); } }); } DelegatingUserManager(Map<String, UserManager>...
@Test public void testGetUserWillNotThrowErrorIfUserManagerDoesNotSupportGetUserMethod() { delegate.put("ext", externalUserManager); delegatingUserManager = new DelegatingUserManager(delegate); try { delegatingUserManager.getUser("test"); } catch (UnsupportedOperationException e) { fail("Should not fail here!"); } }
RescueSecuritySupport extends SecuritySupportBase { @Override public UserManager getUserManager() { log.warn("Using RescueSecuritySupport, will instantiate RescueUserManager, please fix your configuration !"); SystemUserManager userManager = new RescueUserManager(); userManager.setRealmName(Realm.REALM_SYSTEM.getName()...
@Test public void testUserManagerIsAnInstanceOfRescueUserManager() throws Exception { UserManager uman = securitySupport.getUserManager(); assertTrue(uman instanceof RescueUserManager); } @Test public void testUserManagerRealmIsSystemRealm() throws Exception { RescueUserManager uman = (RescueUserManager) securitySuppor...