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 = ((DelegateNodeWrapper) next).deepUnwrap(wrapper); if (deepUnwrappedNext == next) { return this; } try { DelegateNodeWrapper clone = ((DelegateNodeWrapper) this.clone()); clone.initClone(deepUnwrappedNext); return clone; } catch (CloneNotSupportedException e) { throw new RuntimeException("Failed to unwrap " + this.getClass().getName() + " due to " + e.getMessage(), e); } } protected DelegateNodeWrapper(); protected DelegateNodeWrapper(Node node); Node getWrappedNode(); void setWrappedNode(Node node); @Override String toString(); @Override void addMixin(String mixinName); @Override Node addNode(String relPath); @Override Node addNode(String relPath, String primaryNodeTypeName); @Override boolean canAddMixin(String mixinName); @Override void cancelMerge(Version version); @Override Version checkin(); @Override void checkout(); @Override void doneMerge(Version version); @Override void followLifecycleTransition(String transition); @Override String[] getAllowedLifecycleTransistions(); @Override Version getBaseVersion(); @Override String getCorrespondingNodePath(String workspaceName); @Override NodeDefinition getDefinition(); @Override String getIdentifier(); @Override int getIndex(); @Override Lock getLock(); @Override NodeType[] getMixinNodeTypes(); @Override Node getNode(String relPath); @Override NodeIterator getNodes(); @Override NodeIterator getNodes(String namePattern); @Override NodeIterator getNodes(String[] nameGlobs); @Override Item getPrimaryItem(); @Override NodeType getPrimaryNodeType(); @Override PropertyIterator getProperties(); @Override PropertyIterator getProperties(String namePattern); @Override PropertyIterator getProperties(String[] nameGlobs); @Override Property getProperty(String relPath); @Override PropertyIterator getReferences(); @Override PropertyIterator getReferences(String name); @Override NodeIterator getSharedSet(); @Override String getUUID(); @Override VersionHistory getVersionHistory(); @Override PropertyIterator getWeakReferences(); @Override PropertyIterator getWeakReferences(String name); @Override boolean hasNode(String relPath); @Override boolean hasNodes(); @Override boolean hasProperties(); @Override boolean hasProperty(String relPath); @Override boolean holdsLock(); @Override boolean isCheckedOut(); @Override boolean isLocked(); @Override boolean isNodeType(String nodeTypeName); @Override Lock lock(boolean isDeep, boolean isSessionScoped); @Override NodeIterator merge(String srcWorkspace, boolean bestEffort); @Override void orderBefore(String srcChildRelPath, String destChildRelPath); @Override void removeMixin(String mixinName); @Override void removeShare(); @Override void removeSharedSet(); @Override void restore(String versionName, boolean removeExisting); @Override void restore(Version version, boolean removeExisting); @Override void restore(Version version, String relPath, boolean removeExisting); @Override void restoreByLabel(String versionLabel, boolean removeExisting); @Override void setPrimaryType(String nodeTypeName); @Override Property setProperty(String name, Value value); @Override Property setProperty(String name, Value[] values); @Override Property setProperty(String name, String[] values); @Override Property setProperty(String name, String value); @Override Property setProperty(String name, InputStream value); @Override Property setProperty(String name, Binary value); @Override Property setProperty(String name, boolean value); @Override Property setProperty(String name, double value); @Override Property setProperty(String name, BigDecimal value); @Override Property setProperty(String name, long value); @Override Property setProperty(String name, Calendar value); @Override Property setProperty(String name, Node value); @Override Property setProperty(String name, Value value, int type); @Override Property setProperty(String name, Value[] values, int type); @Override Property setProperty(String name, String[] values, int type); @Override Property setProperty(String name, String value, int type); @Override void unlock(); @Override void update(String srcWorkspace); @Override void accept(ItemVisitor visitor); @Override Item getAncestor(int depth); @Override int getDepth(); @Override String getName(); @Override Node getParent(); @Override String getPath(); @Override Session getSession(); @Override boolean isModified(); @Override boolean isNew(); @Override boolean isNode(); @Override boolean isSame(Item otherItem); @Override void refresh(boolean keepChanges); @Override void remove(); @Override void save(); Node deepUnwrap(Class<? extends DelegateNodeWrapper> wrapper); }
@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.deepUnwrap(SecondDelegate.class); assertTrue(test instanceof FirstDelegate); assertTrue(test.getWrappedNode() instanceof SecondDelegate); assertTrue(unwrapped instanceof FirstDelegate); assertTrue(unwrapped.getWrappedNode() instanceof MockNode); assertEquals(((FirstDelegate) test).isTest(), ((FirstDelegate) unwrapped).isTest()); assertTrue(((FirstDelegate) test).getList() == ((FirstDelegate) unwrapped).getList()); Node bareNode = (unwrapped).deepUnwrap(FirstDelegate.class); assertTrue(unwrapped instanceof FirstDelegate); assertTrue(bareNode instanceof MockNode); unwrapped = (DelegateNodeWrapper) test.deepUnwrap(FirstDelegate.class); assertTrue(test instanceof FirstDelegate); assertTrue(test.getWrappedNode() instanceof SecondDelegate); assertTrue(unwrapped instanceof SecondDelegate); assertTrue(unwrapped.getWrappedNode() instanceof MockNode); }
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(), resolveInnerPath()); if(inherited != null){ return inherited.getProperty(relPath); } else { throw new PathNotFoundException("No property exists at " + relPath + " or current Session does not have read access to it."); } } catch (RepositoryException e) { throw new RepositoryException("Can't inherit property " + relPath + " for " + getWrappedNode(), e); } } InheritanceNodeWrapper(Node node); InheritanceNodeWrapper(Node node, AbstractPredicate<Node> filter); InheritanceNodeWrapper(Node node, Node start, AbstractPredicate<Node> filter); InheritanceNodeWrapper(Node node, Node start); @Override boolean hasNode(String relPath); @Override Node getNode(String relPath); @Override NodeIterator getNodes(); @Override NodeIterator getNodes(String namePattern); @Override Property getProperty(String relPath); @Override boolean hasProperty(String name); boolean isInherited(); @Override Node wrapNode(Node node); }
@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("testPropertyInheritance"); Node page11 = getWrapped("/page1/page11"); Node page12 = getWrapped("/page1/page12"); assertEquals("page11", page11.getProperty("nd").getString()); assertEquals("page1", page12.getProperty("nd").getString()); } @Test public void testNestedPropertyInheritance() throws Exception { setUpNode("testNestedPropertyInheritance"); Node comp = getWrapped("/page1/page11/container/comp"); assertEquals("page1", comp.getProperty("nd").getString()); }
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 [" + relPath + "] on node [" + getWrappedNode().getPath() + "]"); } return wrapNode(inherited); } InheritanceNodeWrapper(Node node); InheritanceNodeWrapper(Node node, AbstractPredicate<Node> filter); InheritanceNodeWrapper(Node node, Node start, AbstractPredicate<Node> filter); InheritanceNodeWrapper(Node node, Node start); @Override boolean hasNode(String relPath); @Override Node getNode(String relPath); @Override NodeIterator getNodes(); @Override NodeIterator getNodes(String namePattern); @Override Property getProperty(String relPath); @Override boolean hasProperty(String name); boolean isInherited(); @Override Node wrapNode(Node node); }
@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("/page1/page11/container/comp", containerPage11.getNode("comp").getPath()); assertEquals("/page1/container/comp", containerPage12.getNode("comp").getPath()); assertEquals("/page1/page11/container/comp", page11.getNode("container/comp").getPath()); assertEquals("/page1/container/comp", page12.getNode("container/comp").getPath()); }
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(); boolean executeCommand(final String catalogName, final String commandName, final Map<String, Object> params); boolean executeCommand(final String commandName, final Map<String, Object> params); boolean executeCommand(final Command command, final Map<String, Object> params); static final String DEFAULT_CATALOG; static final String COMMAND_DELIM; }
@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) { return command.getClass().newInstance(); } } catch (IllegalAccessException iae) { log.warn("Cannot create new instance of command [" + commandName + "] from catalog [" + catalogName + "].", iae); } catch (InstantiationException ie) { log.warn("Cannot create new instance of command [" + commandName + "] from catalog [" + catalogName + "].", ie); } } return null; } @Inject CommandsManager(Node2BeanProcessor nodeToBean); Command getCommand(String catalogName, String commandName); Command getCommand(String commandName); @Deprecated static CommandsManager getInstance(); boolean executeCommand(final String catalogName, final String commandName, final Map<String, Object> params); boolean executeCommand(final String commandName, final Map<String, Object> params); boolean executeCommand(final Command command, final Map<String, Object> params); static final String DEFAULT_CATALOG; static final String COMMAND_DELIM; }
@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 be found in catalog [%s]", commandName, catalogName)); } log.debug("Executing command [{}] from catalog [{}] and params [{}]...", new Object[] { commandName, catalogName, params }); return executeCommand(command, params); } @Inject CommandsManager(Node2BeanProcessor nodeToBean); Command getCommand(String catalogName, String commandName); Command getCommand(String commandName); @Deprecated static CommandsManager getInstance(); boolean executeCommand(final String catalogName, final String commandName, final Map<String, Object> params); boolean executeCommand(final String commandName, final Map<String, Object> params); boolean executeCommand(final Command command, final Map<String, Object> params); static final String DEFAULT_CATALOG; static final String COMMAND_DELIM; }
@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()); commandsManager.executeCommand(testCommand, params); Context ctx = testCommand.getContext(); assertNotNull(ctx); assertEquals(ctx.get("mustRead"), "Die Welt als Wille und Vorstellung"); }
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.MetaData.NAME); rule.addAllowType(NodeTypes.Resource.NAME); } return rule; } Rule getRule(); String getItemTypes(); void setItemTypes(String nodeTypes); void setRule(Rule rule); @Override void release(); static final String ATTRIBUTE_RULE; }
@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.isAllowed(content)); }
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(rule.isAllowed(content)); }
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 = MgnlContext.getJCRSession(this.getRepository()).getNode(parentPath); Node toRemove = parentNode.getNode(label); toRemove.remove(); parentNode.getSession().save(); return true; } @Override boolean execute(Context ctx); }
@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.setRepository(WEBSITE); cmd.setPath(firstLevel.getPath()); assertTrue(cmd.execute(ctx)); assertFalse(node.hasNode("first-level")); assertFalse(node.hasNode("first-level/second-level")); } @Test(expected = PathNotFoundException.class) public void testDeleteNonexistentNode() throws Exception { cmd.setRepository(WEBSITE); cmd.setPath("/some/non/existent/path"); cmd.execute(ctx); assertTrue(node.hasNode("first-level")); assertTrue(node.hasNode("first-level/second-level")); }
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)); boolean hasActiveSubscriber = false; for (Subscriber subscriber : ActivationManagerFactory.getActivationManager().getSubscribers()) { if (subscriber.isActive()) { hasActiveSubscriber = true; break; } } if (hasActiveSubscriber || isForcePreDelete()) { preDeleteNode(node, context); } else { node.remove(); parentNode.getSession().save(); } return true; } @Override boolean execute(Context context); boolean isVersionManually(); void setVersionManually(boolean versionManually); boolean isForcePreDelete(); void setForcePreDelete(boolean forcePreDelete); static final String DELETED_NODE_TEMPLATE; static final String DELETED_NODE_DELETED_BY; static final String DELETED_NODE_DELETED_ON; static final String DELETED_NODE_PROP_NAME; }
@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", timeBeforeDelete); node.getSession().save(); MockContext context = (MockContext) MgnlContext.getInstance(); context.setUser(new MgnlUser("user-after-delete","admin",Collections.EMPTY_LIST, Collections.EMPTY_LIST, Collections.EMPTY_MAP, null, null)); cmd.execute(ctx); assertEquals("user-after-delete", NodeTypes.Deleted.getDeletedBy(node)); assertTrue(timeBeforeDelete.getTimeInMillis() < NodeTypes.Deleted.getDeleted(node).getTimeInMillis()); assertEquals("user-after-delete", NodeTypes.Deleted.getDeletedBy(childNode)); assertTrue(timeBeforeDelete.getTimeInMillis() < NodeTypes.Deleted.getDeleted(childNode).getTimeInMillis()); }
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); synchronized Set<K> removeAndPutAll(Collection<K> toRemove, Collection<V> toPut); synchronized Collection<K> keySet(); synchronized Collection<V> values(); }
@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; } 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); synchronized Set<K> removeAndPutAll(Collection<K> toRemove, Collection<V> toPut); synchronized Collection<K> keySet(); synchronized Collection<V> values(); }
@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.getSeparator())) { separator = trail.getSeparator(); } message.append(separator).append(action); if (trail.isActive()) { for (int i = 0; i < data.length; i++) { if (StringUtils.isNotEmpty(data[i])) { message.append(separator).append(data[i]); } } org.apache.log4j.Logger.getLogger(trail.getLogName()).log(LoggingLevel.AUDIT_TRAIL, message.toString()); } } } static AuditLoggingManager getInstance(); void addLogConfigurations(LogConfiguration action); List<LogConfiguration> getLogConfigurations(); void setLogConfigurations(List<LogConfiguration> logConfigurations); LogConfiguration getLogConfiguration(String action); void log(String action, String[] data); String getDefaultSeparator(); void setDefaultSeparator(String defaultSeparator); }
@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, String workspaceName, ItemType nodeType, String nodePath); static void log(String action, String workspaceName, NodeType nodeType, String nodePath); static void log(String action, String workspaceName, String nodePathFrom, String nodePathTo ); static void log(final UserContext userContext ); static void log(final LoginResult loginResult, final HttpServletRequest request ); static final String ACTION_CREATE; static final String ACTION_MODIFY; static final String ACTION_DELETE; static final String ACTION_COPY; static final String ACTION_MOVE; static final String ACTION_ACTIVATE; static final String ACTION_DEACTIVATE; static final String ACTION_LOGIN; static final String ACTION_LOGOUT; }
@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")).andReturn("greg"); expect(request.getRemoteAddr()).andReturn("127.0.0.1"); replay(user, request); AuditLoggingUtil.log(loginResult, request); assertEquals(1, audit.records.size()); assertEquals("login", audit.records.get(0).getLeft()); assertEquals(3, audit.records.get(0).getRight().length); assertEquals("greg", audit.records.get(0).getRight()[0]); assertEquals("127.0.0.1", audit.records.get(0).getRight()[1]); assertEquals("Success", audit.records.get(0).getRight()[2]); verify(user,request); } @Test public void testLogsLoginFailures() { final User user = createStrictMock(User.class); final HttpServletRequest request = createStrictMock(HttpServletRequest.class); final LoginResult loginResult = new LoginResult(LoginResult.STATUS_FAILED, new LoginException("Fail!")); expect(request.getParameter("mgnlUserId")).andReturn("greg"); expect(request.getRemoteAddr()).andReturn("127.0.0.1"); replay(user, request); AuditLoggingUtil.log(loginResult, request); assertEquals(1, audit.records.size()); assertEquals("login", audit.records.get(0).getLeft()); assertEquals(3, audit.records.get(0).getRight().length); assertEquals("greg", audit.records.get(0).getRight()[0]); assertEquals("127.0.0.1", audit.records.get(0).getRight()[1]); assertEquals("Failure Fail!", audit.records.get(0).getRight()[2]); verify(user,request); }
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(new LocaleDefinition("it", null, false)); Node node = new MockNode("foo"); node = node.addNode("de"); node = node.addNode("bar"); MockContent content = new MockContent((MockNode) node); NodeData defaultblah = content.setNodeData("blah", "val_blah"); NodeData localized = defSupport.getNodeData(content, "blah"); assertEquals(defaultblah, localized); NodeData defaultFoo = content.setNodeData("foo", "val_foo"); defSupport.setLocale(new Locale("de")); localized = defSupport.getNodeData(content, "foo"); assertEquals(defaultFoo, localized); node = new MockNode("de_CH"); node = node.addNode("foo"); node = node.addNode("bar"); content = new MockContent((MockNode) node); NodeData swissBlah = content.setNodeData("blah", "val_de_ch_blah"); defSupport.setLocale(new Locale("de", "CH")); localized = defSupport.getNodeData(content, "blah"); assertEquals(swissBlah, localized); defSupport.setLocale(new Locale("de", "AT")); localized = defSupport.getNodeData(content, "blah"); assertEquals(swissBlah, localized); defSupport.setLocale(new Locale("de")); localized = defSupport.getNodeData(content, "blah"); assertEquals(swissBlah, localized); }
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 (RuntimeException) wrapped; } else { throw e; } } static void unwrapIf(RuntimeException e, Class<E> unwrapIf); @SuppressWarnings("unchecked") static void rethrow(Throwable e, Class<? extends Throwable>... allowedExceptions); static boolean wasCausedBy(Throwable e, Class<? extends Throwable> suspectedCause); static String classNameToWords(Exception e); static String exceptionToWords(Exception e); }
@Test public void testUnwrapIfShouldThrowPassedExceptionIfItDoesNotMatchAndIsntARuntimeException() { final IOException originalException = new IOException("AIE"); final RuntimeException runtimeWrapping = new RuntimeException(originalException); try { ExceptionUtil.unwrapIf(runtimeWrapping, RepositoryException.class); fail(); } catch (Throwable t) { assertSame(runtimeWrapping, t); assertSame(originalException, t.getCause()); assertNull(t.getCause().getCause()); } } @Test public void testUnwrapIfWithCauseBeingNull() { final RuntimeException runtimeWrapping = new RuntimeException((Throwable) null); try { ExceptionUtil.unwrapIf(runtimeWrapping, IOException.class); fail(); } catch (Throwable t) { assertSame(runtimeWrapping, t); assertNull(t.getCause()); } } @Test public void testUnwrapIfWithUnwrapIfBeingNull() { final IOException originalException = new IOException("AIE"); final RuntimeException runtimeWrapping = new RuntimeException(originalException); try { ExceptionUtil.unwrapIf(runtimeWrapping, null); fail(); } catch (Throwable t) { assertSame(runtimeWrapping, t); assertSame(originalException, t.getCause()); } }
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)) { sneakyThrow(e); } } throw new Error("Caught the following exception, which was not allowed: ", e); } static void unwrapIf(RuntimeException e, Class<E> unwrapIf); @SuppressWarnings("unchecked") static void rethrow(Throwable e, Class<? extends Throwable>... allowedExceptions); static boolean wasCausedBy(Throwable e, Class<? extends Throwable> suspectedCause); static String classNameToWords(Exception e); static String exceptionToWords(Exception 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 rethrow(Throwable e, Class<? extends Throwable>... allowedExceptions); static boolean wasCausedBy(Throwable e, Class<? extends Throwable> suspectedCause); static String classNameToWords(Exception e); static String exceptionToWords(Exception e); }
@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, Class<? extends Throwable>... allowedExceptions); static boolean wasCausedBy(Throwable e, Class<? extends Throwable> suspectedCause); static String classNameToWords(Exception e); static String exceptionToWords(Exception e); }
@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(RuntimeException e, Class<E> unwrapIf); @SuppressWarnings("unchecked") static void rethrow(Throwable e, Class<? extends Throwable>... allowedExceptions); static boolean wasCausedBy(Throwable e, Class<? extends Throwable> suspectedCause); static String classNameToWords(Exception e); static String exceptionToWords(Exception e); }
@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 wasCausedByReturnsTrueIfDeeperExceptionMatches() { assertTrue(wasCausedBy(new IOException(new RuntimeException(new UnsupportedOperationException(new MgnlException()))), MgnlException.class)); } @Test public void wasCausedByReturnsFalseIfNoCauseInGivenException() { assertFalse(wasCausedBy(new IOException("no cause here"), MgnlException.class)); } @Test public void wasCausedByReturnsFalseIfNoCauseMatches() { assertFalse(wasCausedBy(new IOException(new RuntimeException(new UnsupportedOperationException("no cause here"))), MgnlException.class)); } @Test public void wasCausedByReturnsTrueIfMatchIsASubClass() { assertTrue("preventive check - if this fails, the test has become invalid. The rest of this test class relies on the fact that Content2BeanException is a subclass of MgnlException", MgnlException.class.isAssignableFrom(Content2BeanException.class)); assertTrue(wasCausedBy(new IOException(new Content2BeanException("this is the cause")), MgnlException.class)); } @Test public void wasCausedByReturnsFalseIfMatchIsAParentClass() { assertFalse(wasCausedBy(new IOException(new MgnlException("this is the cause")), Content2BeanException.class)); }
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, valueFactory); } static String getValueString(NodeData nodeData); static String getValueString(NodeData nodeData, String dateFormat); static String getValueString(Value value, String dateFormat); static String inheritString(Content node, String name); static String inheritString(Content node, String name, String dflt); static Object inherit(Content node, String name); static Object inherit(Content node, String name, Object dflt); static Object getValueObject(NodeData nd); static NodeData setValue(NodeData nodeData, Object valueObj); static String getTypeName(NodeData nd); static String getString(String repository, String path); static String getString(Content node, String name); static String getString(String repository, String path, String defaultValue); static String getString(Content node, String name, String defaultValue); static long getLong(Content node, String name, long defaultValue); static Calendar getDate(Content node, String name, Calendar defaultValue); static boolean getBoolean(Content node, String name, boolean defaultValue); static NodeData getOrCreate(Content node, String name); static NodeData getOrCreate(Content node, String name, int type); static NodeData getOrCreate(Content node, String name, Object obj); static NodeData getOrCreateAndSet(Content node, String name, Object obj); static NodeData getOrCreateAndSet(Content node, String name, long value); static NodeData getOrCreateAndSet(Content node, String name, Value[] value); static NodeData getOrCreateAndSet(Content node, String name, int value); static NodeData getOrCreateAndSet(Content node, String name, boolean value); static String getI18NString(Content node, String str); static String getI18NString(Content node, String str, String basename); static Value createValue(String valueStr, int type); @Deprecated static Value createValue(Object obj, ValueFactory valueFactory); @Deprecated static Value createValue(String valueStr, int type, ValueFactory valueFactory); @Deprecated static int getJCRPropertyType(Object obj); @Deprecated static List<String> getValuesStringList(Value[] values); @Deprecated static String getDateFormat(); }
@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 void testCreateValueWithDoubleFromString() throws Exception{ ValueFactory valueFactory = createNiceMock(ValueFactory.class); replay(valueFactory); double three = 3; String obj = "" + three; valueFactory.createValue(three); NodeDataUtil.createValue(obj, PropertyType.DOUBLE, valueFactory); verify(valueFactory); } @Test public void testCreateValueWithFloat() throws Exception{ ValueFactory valueFactory = createNiceMock(ValueFactory.class); replay(valueFactory); float three = 3f; double threeAsDouble = three; Object obj = Float.valueOf(three); valueFactory.createValue(threeAsDouble); NodeDataUtil.createValue(obj, valueFactory); verify(valueFactory); } @Test public void testCreateValueWithInteger() throws Exception{ ValueFactory valueFactory = createNiceMock(ValueFactory.class); replay(valueFactory); int three = 3; long threeAsLong = three; Object obj = Integer.valueOf(three); valueFactory.createValue(threeAsLong); NodeDataUtil.createValue(obj, valueFactory); verify(valueFactory); } @Test public void testCreateValueWithLong() throws Exception{ ValueFactory valueFactory = createNiceMock(ValueFactory.class); replay(valueFactory); long three = 3; Object obj = Long.valueOf(three); valueFactory.createValue(three); NodeDataUtil.createValue(obj, valueFactory); verify(valueFactory); } @Test public void testCreateValueWithLongFromString() throws Exception{ ValueFactory valueFactory = createNiceMock(ValueFactory.class); replay(valueFactory); long three = 3; String obj = "" + three; valueFactory.createValue(three); NodeDataUtil.createValue(obj, PropertyType.LONG, valueFactory); verify(valueFactory); }
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); break; case PropertyType.BOOLEAN: nodeData.setValue(((Boolean)valueObj).booleanValue()); break; case PropertyType.DATE: nodeData.setValue((Calendar)valueObj); break; case PropertyType.LONG: long longToSet = (valueObj instanceof Integer) ? ((Integer) valueObj).longValue() : ((Long) valueObj).longValue(); nodeData.setValue(longToSet); break; case PropertyType.DOUBLE: double doubleToSet = (valueObj instanceof Float) ? ((Float) valueObj).doubleValue() : ((Double) valueObj).doubleValue(); nodeData.setValue(doubleToSet); break; case PropertyType.BINARY: nodeData.setValue((InputStream)valueObj); break; case PropertyType.REFERENCE: nodeData.setValue((Content)valueObj); break; default: nodeData.setValue(valueObj.toString()); } } return nodeData; } static String getValueString(NodeData nodeData); static String getValueString(NodeData nodeData, String dateFormat); static String getValueString(Value value, String dateFormat); static String inheritString(Content node, String name); static String inheritString(Content node, String name, String dflt); static Object inherit(Content node, String name); static Object inherit(Content node, String name, Object dflt); static Object getValueObject(NodeData nd); static NodeData setValue(NodeData nodeData, Object valueObj); static String getTypeName(NodeData nd); static String getString(String repository, String path); static String getString(Content node, String name); static String getString(String repository, String path, String defaultValue); static String getString(Content node, String name, String defaultValue); static long getLong(Content node, String name, long defaultValue); static Calendar getDate(Content node, String name, Calendar defaultValue); static boolean getBoolean(Content node, String name, boolean defaultValue); static NodeData getOrCreate(Content node, String name); static NodeData getOrCreate(Content node, String name, int type); static NodeData getOrCreate(Content node, String name, Object obj); static NodeData getOrCreateAndSet(Content node, String name, Object obj); static NodeData getOrCreateAndSet(Content node, String name, long value); static NodeData getOrCreateAndSet(Content node, String name, Value[] value); static NodeData getOrCreateAndSet(Content node, String name, int value); static NodeData getOrCreateAndSet(Content node, String name, boolean value); static String getI18NString(Content node, String str); static String getI18NString(Content node, String str, String basename); static Value createValue(String valueStr, int type); @Deprecated static Value createValue(Object obj, ValueFactory valueFactory); @Deprecated static Value createValue(String valueStr, int type, ValueFactory valueFactory); @Deprecated static int getJCRPropertyType(Object obj); @Deprecated static List<String> getValuesStringList(Value[] values); @Deprecated static String getDateFormat(); }
@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); NodeDataUtil.setValue(data, Float.valueOf(3)); assertEquals(3.0, data.getDouble(), 0.0); }
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(0, comparator.compare(a, otherA)); assertTrue(comparator.compare(a, b) < 0); assertTrue(comparator.compare(b, a) > 0); }
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-app/webxml:filter-mapping[webxml:filter-name='" + filterName + "']/webxml:dispatcher"; final List dispatchersEl = getElementsFromXPath(filterMappingXPathExpr); final List registeredDispatchers = new ArrayList(); final Iterator it = dispatchersEl.iterator(); while (it.hasNext()) { final Element dispatcherEl = (Element) it.next(); registeredDispatchers.add(dispatcherEl.getTextNormalize()); } registeredDispatchers.removeAll(optionalDispatchers); if (CollectionUtils.isEqualCollection(mandatoryDispatchers, registeredDispatchers)) { return 1; } else if (CollectionUtils.isSubCollection(mandatoryDispatchers, registeredDispatchers)) { return 0; } else { return -1; } } return 1; } WebXmlUtil(); WebXmlUtil(InputStream inputStream); boolean isServletOrMappingRegistered(String servletName); boolean isServletRegistered(String servletName); boolean isServletMappingRegistered(String servletName); boolean isServletMappingRegistered(String servletName, String urlPattern); Collection getServletMappings(String servletName); boolean isFilterRegistered(String filterClass); boolean areFilterDispatchersConfiguredProperly(String filterClass, List mandatoryDispatchers, List optionalDispatchers); int checkFilterDispatchersConfiguration(String filterClass, List mandatoryDispatchers, List optionalDispatchers); boolean isListenerRegistered(String deprecatedListenerClass); }
@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 public void testFilterDispatcherChecksShouldFailIfDispatcherNotSet() { WebXmlUtil util = new WebXmlUtil(getClass().getResourceAsStream("web_filternodispatcher.xml")); assertEquals(-1, util.checkFilterDispatchersConfiguration(MgnlMainFilter.class.getName(), MANDATORY_DISPATCHERS, OPTIONAL_DISPATCHERS)); } @Test public void testFilterDispatcherChecksShouldNotFailIfFilterNotRegistered() { WebXmlUtil util = new WebXmlUtil(getClass().getResourceAsStream("web_nofilter.xml")); assertEquals(1, util.checkFilterDispatchersConfiguration(MgnlMainFilter.class.getName(), MANDATORY_DISPATCHERS, OPTIONAL_DISPATCHERS)); } @Test public void testFilterDispatcherChecksShouldFailIfRequestIsMissing() { WebXmlUtil util = new WebXmlUtil(getClass().getResourceAsStream("web_filterwrongdispatchers.xml")); assertEquals(-1, util.checkFilterDispatchersConfiguration("webxmltest.WithMissingForward", MANDATORY_DISPATCHERS, OPTIONAL_DISPATCHERS)); } @Test public void testFilterDispatcherChecksShouldFailIfIncludeIsMissing() { WebXmlUtil util = new WebXmlUtil(getClass().getResourceAsStream("web_filterwrongdispatchers.xml")); assertEquals(-1, util.checkFilterDispatchersConfiguration("webxmltest.WithMissingInclude", MANDATORY_DISPATCHERS, OPTIONAL_DISPATCHERS)); } @Test public void testFilterDispatcherErrorIsNotMandatory() { WebXmlUtil util = new WebXmlUtil(getClass().getResourceAsStream("web_filterwrongdispatchers.xml")); assertEquals(1, util.checkFilterDispatchersConfiguration("webxmltest.ErrorIsNotMandatory", MANDATORY_DISPATCHERS, OPTIONAL_DISPATCHERS)); } @Test public void testFilterDispatcherOrderIsIrrelevant() { WebXmlUtil util = new WebXmlUtil(getClass().getResourceAsStream("web_filterwrongdispatchers.xml")); assertEquals(1, util.checkFilterDispatchersConfiguration("webxmltest.OrderIsIrrelevant", MANDATORY_DISPATCHERS, OPTIONAL_DISPATCHERS)); }
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 servletName); boolean isServletMappingRegistered(String servletName, String urlPattern); Collection getServletMappings(String servletName); boolean isFilterRegistered(String filterClass); boolean areFilterDispatchersConfiguredProperly(String filterClass, List mandatoryDispatchers, List optionalDispatchers); int checkFilterDispatchersConfiguration(String filterClass, List mandatoryDispatchers, List optionalDispatchers); boolean isListenerRegistered(String deprecatedListenerClass); }
@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 = extendedContent.getContent(name); } else { content = getWrappedContent().getContent(name); } return wrap(content); } ExtendingContentWrapper(Content wrappedContent, boolean failOnError); ExtendingContentWrapper(Content wrappedContent); protected ExtendingContentWrapper(Content wrappedContent, Content extendedContent); boolean isExtending(); @Override Content getWrappedContent(); @Override boolean hasContent(String name); @Override Content getContent(String name); @Override Collection<Content> getChildren(ContentFilter filter, String namePattern, Comparator<Content> orderCriteria); @Override NodeData getNodeData(String name); @Override boolean hasNodeData(String name); @Override Collection<NodeData> getNodeDataCollection(); }
@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" + "/impl/node3/extends=../../superbase/wrongNode"); try { Content plainContent = hm.getContent("/impl/node3"); new ExtendingContentWrapper(plainContent, true); fail("Must never get here!"); } catch (RuntimeException e) { assertEquals("Can't find referenced node for value: testSession:/impl/node3[mgnl:contentNode]", e.getMessage()); } } @Test public void testExtendsAbsolutelyAndNodeIsNotExisting() throws IOException, RepositoryException { HierarchyManager hm = MockUtil.createHierarchyManager( "/impl/node/extends=/base/node\n" + "/impl/node/nodeData2=org2"); Content plainContent = hm.getContent("/impl/node"); try { new ExtendingContentWrapper(plainContent, true); fail("should never get here..."); } catch (RuntimeException e) { assertEquals("Can't find referenced node for value: testSession:/impl/node[mgnl:contentNode]", e.getMessage()); } }
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); final File sourceDir = new File(dir); File[] files = sourceDir.listFiles(); if (files == null) { return names; } final SAXBuilder builder = new SAXBuilder(); for (File f : files) { if (!f.isDirectory()) { continue; } final File wks = new File(f, "workspace.xml"); if (!wks.exists() || !wks.canRead()) { continue; } try { log.debug("Analysing file " + wks.getAbsolutePath()); final List<Attribute> list = getElementsFromXPath(builder.build(wks), xPathExpression); if (expectation == null) { if (list.size() == 0) { names.add(wks.getAbsolutePath()); } } else { if (list.size() > 0 && list.get(0).getValue().matches(expectation)) { names.add(wks.getAbsolutePath()); } } } catch (JDOMException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } return names; } static List<String> getWorkspaceNamesWithIndexer(); static List<String> getWorkspaceNamesMatching(String xPathExpression); static List<String> getWorkspaceNames(String xPathExpression, String expectation); }
@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).contains("/outdated/workspace.xml")); } @Test public void testWorkspaceNamesWithNullExpectation() { List<String> names = WorkspaceXmlUtil.getWorkspaceNames("/Workspace/SearchIndex/param[@name='textFilterClasses']/@value", null); assertEquals("Found incorrect amount of indexers", 1, names.size()); assertTrue(names.get(0).contains("/current/workspace.xml")); }
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.getNodeData(name); } } catch (RepositoryException e) { throw new RuntimeException("Can't inherit nodedata " + name + " for " + getWrappedContent(), e); } return super.getNodeData(name); } InheritanceContentWrapper(Content wrappedContent, Content start); InheritanceContentWrapper(Content node); @Override boolean hasContent(String name); @Override Content getContent(String name); @Override Collection<Content> getChildren(ContentFilter filter, String namePattern, Comparator<Content> orderCriteria); @Override NodeData getNodeData(String name); @Override boolean hasNodeData(String name); boolean isInherited(); }
@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 Exception { setUpContent("testPropertyInheritance"); Content page11 = getWrapped("/page1/page11"); Content page12 = getWrapped("/page1/page12"); assertEquals("page11", page11.getNodeData("nd").getString()); assertEquals("page1", page12.getNodeData("nd").getString()); } @Test public void testNestedPropertyInheritance() throws Exception { setUpContent("testNestedPropertyInheritance"); Content para = getWrapped("/page1/page11/container/para"); assertEquals("page1", para.getNodeData("nd").getString()); }
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() + "]"); } return inherited; } InheritanceContentWrapper(Content wrappedContent, Content start); InheritanceContentWrapper(Content node); @Override boolean hasContent(String name); @Override Content getContent(String name); @Override Collection<Content> getChildren(ContentFilter filter, String namePattern, Comparator<Content> orderCriteria); @Override NodeData getNodeData(String name); @Override boolean hasNodeData(String name); boolean isInherited(); }
@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("container"); assertEquals("/page1/page11/container/para", containerPage11.getContent("para").getHandle()); assertEquals("/page1/container/para", containerPage12.getContent("para").getHandle()); assertEquals("/page1/page11/container/para", page11.getContent("container/para").getHandle()); assertEquals("/page1/container/para", page12.getContent("container/para").getHandle()); }
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 != null) { return inherited.hasNodeData(name); } } catch (RepositoryException e) { throw new RuntimeException("Can't inherit nodedata " + name + " for " + getWrappedContent(), e); } return super.hasNodeData(name); } InheritanceContentWrapper(Content wrappedContent, Content start); InheritanceContentWrapper(Content node); @Override boolean hasContent(String name); @Override Content getContent(String name); @Override Collection<Content> getChildren(ContentFilter filter, String namePattern, Comparator<Content> orderCriteria); @Override NodeData getNodeData(String name); @Override boolean hasNodeData(String name); boolean isInherited(); }
@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 testHasNestedPropertyInheritance() throws Exception { setUpContent("testNestedPropertyInheritance"); Content para = getWrapped("/page1/page11/container/para"); assertTrue(para.hasNodeData("nd")); }
SystemContentWrapper extends LazyContentWrapper { @Override public HierarchyManager getHierarchyManager() { return LifeTimeJCRSessionUtil.getHierarchyManager(getRepository()); } SystemContentWrapper(String repository, String uuid); SystemContentWrapper(Content node); @Override HierarchyManager getHierarchyManager(); @Override NodeData wrap(NodeData nodeData); }
@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"); hm.save(); Content plainContent = hm.getContent("/bla"); Content systemContent = new SystemContentWrapper(plainContent); NodeData nd = systemContent.getNodeData("nodeData2"); hm.getWorkspace().getSession().logout(); assertFalse(plainContent.getWorkspace().getSession().isLive()); assertTrue(systemContent.getWorkspace().getSession().isLive()); assertEquals(systemContent.getHierarchyManager(), LifeTimeJCRSessionUtil.getHierarchyManager("config")); assertEquals(systemContent.getHierarchyManager(), nd.getHierarchyManager()); } @Test public void testWrappingNDParent() throws Exception { HierarchyManager hm = MgnlContext.getInstance().getHierarchyManager("config"); assertNotSame(hm, LifeTimeJCRSessionUtil.getHierarchyManager("config")); hm.getRoot().createContent("bla", ItemType.CONTENT.getSystemName()).setNodeData("nodeData2", "boo"); hm.save(); Content plainContent = hm.getContent("/bla"); Content systemContent = new SystemContentWrapper(plainContent); NodeData nd = systemContent.getNodeData("nodeData2"); assertTrue(nd.getParent() instanceof SystemContentWrapper); } @Test public void testWrappingReferencedContent() throws Exception { HierarchyManager hm = MgnlContext.getInstance().getHierarchyManager("config"); assertNotSame(hm, LifeTimeJCRSessionUtil.getHierarchyManager("config")); hm.getRoot().createContent("bla", ItemType.CONTENT.getSystemName()).setNodeData("nodeData2", "/boo"); hm.getRoot().createContent("boo", ItemType.CONTENT.getSystemName()); hm.save(); Content plainContent = hm.getContent("/bla"); Content systemContent = new SystemContentWrapper(plainContent); Content referencedContent = systemContent.getNodeData("nodeData2").getReferencedContent(); assertTrue(referencedContent instanceof SystemContentWrapper); referencedContent = systemContent.getNodeData("nodeData2").getReferencedContent("config"); assertTrue(referencedContent instanceof SystemContentWrapper); }
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 StringBuffer(); final Matcher matcher = searchPattern.matcher(oldValue); int count = 0; while (matcher.find()) { final String group = matcher.group(); matcher.appendReplacement(newValue, replace); count++; } matcher.appendTail(newValue); onPropertyVisit(prop, count, oldValue, newValue); prop.setValue(newValue.toString()); } } } SearchReplace(String propertyNamePattern, String search, String replace); SearchReplace(String propertyNamePattern, String search, String replace, int regexFlags); @Override void visit(Content node); }
@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 MAGNOLIA are the rules", prop("/top/other3/text")); ContentUtil.visit(root, new SearchReplace("text", "magnolia", "Magnolia", Pattern.CASE_INSENSITIVE)); 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 Magnolia are the rules", prop("/top/other3/text")); } @Test public void testCanUseNamePatterns() throws Exception { assertEquals("three flowers", prop("/top/plip/text")); assertEquals("three flowers", prop("/top/plip/other")); assertEquals("three flowers", prop("/top/plip/title")); ContentUtil.visit(root, new SearchReplace("other|text", "flower", "Magnolia", Pattern.CASE_INSENSITIVE)); assertEquals("three Magnolias", prop("/top/plip/text")); assertEquals("three Magnolias", prop("/top/plip/other")); assertEquals("three flowers", prop("/top/plip/title")); } @Test public void testCanUseJokerInNamePatterns() throws Exception { assertEquals("three flowers", prop("/top/plip/text")); assertEquals("three flowers", prop("/top/plip/other")); assertEquals("three flowers", prop("/top/plip/title")); ContentUtil.visit(root, new SearchReplace("t*", "flower", "Magnolia", Pattern.CASE_INSENSITIVE)); assertEquals("three Magnolias", prop("/top/plip/text")); assertEquals("three Magnolias", prop("/top/plip/title")); assertEquals("three flowers", prop("/top/plip/other")); } @Test public void testDefaultsToLiteralMatching() throws Exception { assertEquals("This property contains an [ open bracket.", prop("/top/blah/text")); assertEquals("This property contains an { open bracketZ", prop("/top/bloh/text")); assertEquals("This property contains what looks like [a-z] regex class", prop("/top/bluh/regextest")); ContentUtil.visit(root, new SearchReplace("text", "[", "(")); ContentUtil.visit(root, new SearchReplace("text", "bracket.", "parenthesis.")); ContentUtil.visit(root, new SearchReplace("regextest", "[a-z]", "a")); assertEquals("This property contains an ( open parenthesis.", prop("/top/blah/text")); assertEquals("This property contains an { open bracketZ", prop("/top/bloh/text")); assertEquals("This property contains what looks like a regex class", prop("/top/bluh/regextest")); }
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 (lastDot > lastSlash && lastDot != -1) { fingerprintedLink = link.substring(0, lastDot) + "." + fingerprint + link.substring(lastDot); } else { fingerprintedLink = link + "." + fingerprint; } return fingerprintedLink; } static String addFingerprintToLink(String link, Calendar lastModified); static String removeFingerprintAndExtensionFromLink(String originalPath); }
@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.addFingerprintToLink(link, calendar1); assertFalse(link.equals(link1)); assertTrue(link1.indexOf(".png") > 0); } @Test public void testAddFingerprintToLinkCompareTwoDates() throws Exception { String link1 = LinkUtil.addFingerprintToLink(link, calendar1); String fLinkPast = LinkUtil.addFingerprintToLink(link, calendar2); assertNotEquals(fLinkPast, link1); } @Test public void testAddFingerprintToLinkWithoutExtension() throws Exception { String link1 = LinkUtil.addFingerprintToLink(linkNoExtension, calendar1); String link2 = LinkUtil.addFingerprintToLink(linkNoExtension, calendar2); assertNotEquals(link, link1); assertNotEquals(link2, link1); } @Test public void testAddFingerprintToLinkWithInvalidDate() throws Exception { String link1 = LinkUtil.addFingerprintToLink(link, null); assertEquals(link, link1); }
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}")) { return StringUtils.substringBeforeLast(subPath, "."); } else { return subPath; } } static String addFingerprintToLink(String link, Calendar lastModified); static String removeFingerprintAndExtensionFromLink(String originalPath); }
@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 statement); static Collection<Content> query(String repository, String statement, String language); static Collection<Content> exceptionThrowingQuery(String repository, String statement, String language, String returnItemType); static Collection<Content> exceptionThrowingQuery(String repository, String statement, String language, String returnItemType, long maxResultSize); static Collection<Content> query(String repository, String statement, String language, String returnItemType); @SuppressWarnings("unchecked") // Collections.EMPTY_LIST; static Collection<Content> query(String repository, String statement, String language, String returnItemType, long maxResultSize); static String createDateExpression(int year, int month, int day); static String createDateExpression(Calendar calendar); static String createDateTimeExpression(int year, int month, int day, int hour, int minutes, int seconds); static String createDateTimeExpression(Calendar calendar); static String createDateTimeExpressionIgnoreTimeZone(int year, int month, int day, int hour, int minutes, int seconds); static String createDateTimeExpressionIgnoreTimeZone(Calendar calendar); static NodeIterator search(QueryObjectModel model, String returnItemType); static NodeIterator search(String workspace, String statement, String language); static NodeIterator search(String workspace, String statement); static NodeIterator search(String workspace, String statement, String language, String returnItemType); static String buildQuery(String statement, String startPath); }
@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 public void testResultContainsOnlyPages() throws InvalidQueryException, RepositoryException{ String statement = "select * from [mgnl:page]"; NodeIterator result = QueryUtil.search("website", statement); while(result.hasNext()){ assertEquals(NodeTypes.Page.NAME, result.nextNode().getPrimaryNodeType().getName()); } } @Test public void testSearchOfNonDefaultNodeType() throws InvalidQueryException, RepositoryException{ String statement = "select * from [mgnl:component]"; NodeIterator result = QueryUtil.search("website", statement, Query.JCR_SQL2); while(result.hasNext()){ assertEquals(NodeTypes.Component.NAME, result.nextNode().getPrimaryNodeType().getName()); } } @Test public void testSearchForUUID() throws InvalidQueryException, RepositoryException{ String statement = "select * from [nt:base] where [jcr:uuid] = 'c1fcda79-1f81-412d-a748-b9ea34ea97f7'"; NodeIterator result = QueryUtil.search("website", statement); Collection<Node> collection = NodeUtil.getCollectionFromNodeIterator(result); assertEquals(1, collection.size()); } @Test public void testSearchForInheritedUUID() throws InvalidQueryException, RepositoryException{ String statement = "select * from [mgnl:area] where [jcr:uuid] = '6ecc7d08-9329-44ca-bfc7-ab7b73f6f64d'"; NodeIterator result = QueryUtil.search("website", statement, Query.JCR_SQL2); Collection<Node> collection = NodeUtil.getCollectionFromNodeIterator(result); assertEquals(1, collection.size()); } @Test public void testSearchForUUIDInChildNode() throws InvalidQueryException, RepositoryException{ String statement = "select * from [nt:base] where [jcr:uuid] = '6ecc7d08-9329-44ca-bfc7-ab7b73f6f64d'"; NodeIterator iterator = QueryUtil.search("website", statement, Query.JCR_SQL2, NodeTypes.Page.NAME); assertEquals("/queryTest", iterator.nextNode().getPath()); } @Test public void testSearchForSpecificTemplate() throws InvalidQueryException, RepositoryException{ String statement = "select * from [nt:base] where [mgnl:template] = 'standard-templating-kit:pages/stkArticle'"; NodeIterator iterator = QueryUtil.search("website", statement, Query.JCR_SQL2, NodeTypes.Page.NAME); assertEquals(2, NodeUtil.getCollectionFromNodeIterator(iterator).size()); } @Test public void testEmptyResult() throws InvalidQueryException, RepositoryException{ String statement = "select * from [nt:base] where [jcr:uuid] = 'non-existing'"; NodeIterator result = QueryUtil.search("website", statement); assertFalse(result.hasNext()); } @Test public void testJQOM() throws InvalidQueryException, RepositoryException{ Session session = MgnlContext.getJCRSession("website"); QueryObjectModelFactory factory = session.getWorkspace().getQueryManager().getQOMFactory(); QueryObjectModelBuilder qom = new SQL2QOMBuilder(); String statement = "select * from [nt:base] where [jcr:uuid] = 'c1fcda79-1f81-412d-a748-b9ea34ea97f7'"; QueryObjectModel model = qom.createQueryObjectModel(statement, factory, session.getValueFactory()); NodeIterator result = QueryUtil.search(model, NodeTypes.Page.NAME); Collection<Node> collection = NodeUtil.getCollectionFromNodeIterator(result); assertEquals(1, collection.size()); } @Test public void testQueryWhenSearchingJustForPages() throws InvalidQueryException, RepositoryException{ String statement = "select * from [nt:base]"; NodeIterator result = QueryUtil.search("website", statement, Query.JCR_SQL2, NodeTypes.Page.NAME); int count = 0; while(result.hasNext()){ Node node = result.nextNode(); assertEquals(NodeTypes.Page.NAME, node.getPrimaryNodeType().getName()); count++; } assertEquals(7, count); } @Test public void testQueryWhenSearchingJustForComponents() throws InvalidQueryException, RepositoryException{ String statement = "select * from [nt:base]"; NodeIterator result = QueryUtil.search("website", statement, Query.JCR_SQL2, NodeTypes.Component.NAME); int count = 0; while(result.hasNext()){ assertEquals(NodeTypes.Component.NAME, result.nextNode().getPrimaryNodeType().getName()); count++; } assertEquals(5, count); } @Test public void testSearchForPagesWhoseComponentIsContainingSpecificText() throws InvalidQueryException, RepositoryException{ String statement = "select * from [mgnl:component] as t where contains(t.*, 'TestText')"; NodeIterator result = QueryUtil.search("website", statement, Query.JCR_SQL2, NodeTypes.Page.NAME); int count = 0; while(result.hasNext()){ assertEquals(NodeTypes.Page.NAME, result.nextNode().getPrimaryNodeType().getName()); count++; } assertEquals(2, count); } @Test public void testSearchForAreasContainingImage() throws InvalidQueryException, RepositoryException{ String statement = "select * from [mgnl:component] where image is not null"; NodeIterator result = QueryUtil.search("website", statement, Query.JCR_SQL2, NodeTypes.Area.NAME); while(result.hasNext()){ Node node = result.nextNode(); assertEquals(NodeTypes.Area.NAME, node.getPrimaryNodeType().getName()); assertEquals("/queryTest/subPage2/subPage2/content", node.getPath()); } } @Test public void testConfirmThatFilteredResultIsReallyTheWantedOne() throws InvalidQueryException, RepositoryException{ String statement = "select * from [nt:base] as t where contains(t.*, 'Poughkeepsie')"; NodeIterator result = QueryUtil.search("website", statement); assertEquals(NodeTypes.Component.NAME, result.nextNode().getPrimaryNodeType().getName()); result = QueryUtil.search("website", statement, Query.JCR_SQL2, NodeTypes.Page.NAME); assertEquals(NodeTypes.Page.NAME, result.nextNode().getPrimaryNodeType().getName()); }
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(["+startPath+"])"; while(argIt.hasNext()){ queryString = queryString + " AND contains(t.*, '"+argIt.next()+"')"; } log.debug("query string: " + queryString); return queryString; } static Collection<Content> query(String repository, String statement); static Collection<Content> query(String repository, String statement, String language); static Collection<Content> exceptionThrowingQuery(String repository, String statement, String language, String returnItemType); static Collection<Content> exceptionThrowingQuery(String repository, String statement, String language, String returnItemType, long maxResultSize); static Collection<Content> query(String repository, String statement, String language, String returnItemType); @SuppressWarnings("unchecked") // Collections.EMPTY_LIST; static Collection<Content> query(String repository, String statement, String language, String returnItemType, long maxResultSize); static String createDateExpression(int year, int month, int day); static String createDateExpression(Calendar calendar); static String createDateTimeExpression(int year, int month, int day, int hour, int minutes, int seconds); static String createDateTimeExpression(Calendar calendar); static String createDateTimeExpressionIgnoreTimeZone(int year, int month, int day, int hour, int minutes, int seconds); static String createDateTimeExpressionIgnoreTimeZone(Calendar calendar); static NodeIterator search(QueryObjectModel model, String returnItemType); static NodeIterator search(String workspace, String statement, String language); static NodeIterator search(String workspace, String statement); static NodeIterator search(String workspace, String statement, String language, String returnItemType); static String buildQuery(String statement, String startPath); }
@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(redirectUrl)) { redirectUrl = request.getContextPath() + redirectUrl; } response.sendRedirect(response.encodeRedirectURL(redirectUrl)); } catch (IOException e) { log.error("Failed to redirect to {}:{}", targetUri, e.getMessage()); } return true; } if (targetUri.startsWith(PERMANENT_PREFIX)) { String permanentUrl = StringUtils.substringAfter(targetUri, PERMANENT_PREFIX); try { if (isInternal(permanentUrl)){ if (isUsingStandardPort(request)) { permanentUrl = new URL( request.getScheme(), request.getServerName(), request.getContextPath() + permanentUrl).toExternalForm(); } else { permanentUrl = new URL( request.getScheme(), request.getServerName(), request.getServerPort(), request.getContextPath() + permanentUrl).toExternalForm(); } } response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); response.setHeader("Location", permanentUrl); } catch (MalformedURLException e) { log.error("Failed to create permanent url to redirect to {}:{}", targetUri, e.getMessage()); } return true; } if (targetUri.startsWith(FORWARD_PREFIX)) { String forwardUrl = StringUtils.substringAfter(targetUri, FORWARD_PREFIX); try { request.getRequestDispatcher(forwardUrl).forward(request, response); } catch (Exception e) { log.error("Failed to forward to {} - {}:{}", new Object[]{ forwardUrl, ClassUtils.getShortClassName(e.getClass()), e.getMessage()}); } return true; } return false; } static boolean dispatch(String targetUri, HttpServletRequest request, HttpServletResponse response); static final String REDIRECT_PREFIX; static final String PERMANENT_PREFIX; static final String FORWARD_PREFIX; }
@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 = RequestDispatchUtil.REDIRECT_PREFIX + FRAGMENT; HttpServletRequest request = createNiceMock(HttpServletRequest.class); HttpServletResponse response = createNiceMock(HttpServletResponse.class); expect(request.getContextPath()).andReturn(contextPath); expect(response.encodeRedirectURL(contextPath + FRAGMENT)).andReturn(contextPath + ENCODED_FRAGMENT); response.sendRedirect(contextPath + ENCODED_FRAGMENT); Object[] mocks = new Object[] {request, response}; replay(mocks); boolean result = RequestDispatchUtil.dispatch(targetUri, request, response); assertTrue(result); verify(mocks); } @Test public void testDispatchRedirectNonInternal() throws Exception { final String targetUri = RequestDispatchUtil.REDIRECT_PREFIX + EXTERNAL_URL + FRAGMENT; HttpServletRequest request = createNiceMock(HttpServletRequest.class); HttpServletResponse response = createNiceMock(HttpServletResponse.class); expect(response.encodeRedirectURL(EXTERNAL_URL + FRAGMENT)).andReturn(EXTERNAL_URL + ENCODED_FRAGMENT); response.sendRedirect(EXTERNAL_URL + ENCODED_FRAGMENT); Object[] mocks = new Object[] {request, response}; replay(mocks); boolean result = RequestDispatchUtil.dispatch(targetUri, request, response); assertTrue(result); verify(mocks); } @Test public void testDispatchRedirectNonInternalFailure() throws Exception{ final String targetUri = RequestDispatchUtil.REDIRECT_PREFIX + EXTERNAL_URL + FRAGMENT; HttpServletRequest request = createNiceMock(HttpServletRequest.class); HttpServletResponse response = createNiceMock(HttpServletResponse.class); expect(response.encodeRedirectURL(EXTERNAL_URL + FRAGMENT)).andReturn(EXTERNAL_URL + ENCODED_FRAGMENT); response.sendRedirect(EXTERNAL_URL + ENCODED_FRAGMENT); Exception exception = new IOException("Something went wrong!"); expectLastCall().andThrow(exception); Object[] mocks = new Object[] {request, response}; replay(mocks); boolean result = RequestDispatchUtil.dispatch(targetUri, request, response); assertTrue(result); verify(mocks); }
ModuleConfigurationObservingManager { public void start() { for (String moduleName : moduleRegistry.getModuleNames()) { String path = "/modules/" + moduleName + "/" + pathWithinModule; observedPaths.add(path); } final EventListener eventListener = ObservationUtil.instanciateDeferredEventListener(new EventListener() { @Override public void onEvent(EventIterator events) { synchronized (reloadMonitor) { MgnlContext.doInSystemContext(new MgnlContext.VoidOp(){ @Override public void doExec() { reload(); } }, true); } } }, 1000, 5000); for (String observedPath : observedPaths) { ObservationUtil.registerChangeListener(RepositoryConstants.CONFIG, observedPath, new EventListener(){ @Override public void onEvent(EventIterator events) { eventListener.onEvent(events); } }); } synchronized (reloadMonitor) { reload(); } } protected ModuleConfigurationObservingManager(String pathWithinModule, ModuleRegistry moduleRegistry); void start(); }
@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.CONFIG, session); Set<String> moduleNames = new LinkedHashSet<String>(); moduleNames.add("foo"); moduleNames.add("bar"); moduleNames.add("zed"); ModuleRegistry moduleRegistry = mock(ModuleRegistry.class); when(moduleRegistry.getModuleNames()).thenReturn(moduleNames); final AtomicInteger clearCounter = new AtomicInteger(0); final List<String> pathsOfReloadedNodes = new ArrayList<String>(); ModuleConfigurationObservingManager observingManager = new ModuleConfigurationObservingManager("components", moduleRegistry) { @Override protected void onClear() throws RepositoryException { clearCounter.incrementAndGet(); } @Override protected void onRegister(Node node) throws RepositoryException { pathsOfReloadedNodes.add(node.getPath()); if (latch != null) { latch.countDown(); } } }; observingManager.start(); assertEquals(1, clearCounter.get()); assertEquals(2, pathsOfReloadedNodes.size()); assertEquals("/modules/foo/components", pathsOfReloadedNodes.get(0)); assertEquals("/modules/bar/components", pathsOfReloadedNodes.get(1)); session.getNode("/modules/zed").addNode("components"); MockObservationManager observationManager = (MockObservationManager) session.getWorkspace().getObservationManager(); for (String moduleName : moduleNames) { MockEvent event = MockEvent.nodeAdded("/modules/" + moduleName + "/components/a"); verifyReloadsAllNodesOnEvent(clearCounter, pathsOfReloadedNodes, observationManager, event); } for (String moduleName : moduleNames) { MockEvent event = MockEvent.propertyAdded("/modules/" + moduleName + "/components" + "@property"); verifyReloadsAllNodesOnEvent(clearCounter, pathsOfReloadedNodes, observationManager, event); } }
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) parameterNames.nextElement(); initParameters.put(parameterName, config.getInitParameter(parameterName)); } return initParameters; } static LinkedHashMap<String, String> initParametersToMap(ServletConfig config); static LinkedHashMap<String, String> initParametersToMap(FilterConfig config); static T getWrappedRequest(ServletRequest request, Class<T> clazz); static boolean isMultipart(HttpServletRequest request); static boolean isForward(HttpServletRequest request); static boolean isInclude(HttpServletRequest request); static boolean isError(HttpServletRequest request); static DispatcherType getDispatcherType(HttpServletRequest request); static String getOriginalRequestURI(HttpServletRequest request); static String getOriginalRequestURLIncludingQueryString(HttpServletRequest request); static String getRequestUri(HttpServletRequest request); static final String FORWARD_REQUEST_URI_ATTRIBUTE; static final String FORWARD_QUERY_STRING_ATTRIBUTE; static final String INCLUDE_REQUEST_URI_ATTRIBUTE; static final String ERROR_REQUEST_STATUS_CODE_ATTRIBUTE; }
@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", null, initParameters); LinkedHashMap<String, String> map = ServletUtil.initParametersToMap(servletConfig); assertEquals(3, map.size()); assertEquals("value1", map.get("key1")); String[] strings = map.keySet().toArray(new String[3]); assertEquals("key1", strings[0]); assertEquals("key2", strings[1]); assertEquals("key3", strings[2]); } @Test public void testFilterInitParametersToMap() { LinkedHashMap<String, String> initParameters = new LinkedHashMap<String, String>(); initParameters.put("key1", "value1"); initParameters.put("key2", "value2"); initParameters.put("key3", "value3"); CustomFilterConfig servletConfig = new CustomFilterConfig("filter", null, initParameters); LinkedHashMap<String, String> map = ServletUtil.initParametersToMap(servletConfig); assertEquals(3, map.size()); assertEquals("value1", map.get("key1")); String[] strings = map.keySet().toArray(new String[3]); assertEquals("key1", strings[0]); assertEquals("key2", strings[1]); assertEquals("key3", strings[2]); }
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() : null; } return null; } static LinkedHashMap<String, String> initParametersToMap(ServletConfig config); static LinkedHashMap<String, String> initParametersToMap(FilterConfig config); static T getWrappedRequest(ServletRequest request, Class<T> clazz); static boolean isMultipart(HttpServletRequest request); static boolean isForward(HttpServletRequest request); static boolean isInclude(HttpServletRequest request); static boolean isError(HttpServletRequest request); static DispatcherType getDispatcherType(HttpServletRequest request); static String getOriginalRequestURI(HttpServletRequest request); static String getOriginalRequestURLIncludingQueryString(HttpServletRequest request); static String getRequestUri(HttpServletRequest request); static final String FORWARD_REQUEST_URI_ATTRIBUTE; static final String FORWARD_QUERY_STRING_ATTRIBUTE; static final String INCLUDE_REQUEST_URI_ATTRIBUTE; static final String ERROR_REQUEST_STATUS_CODE_ATTRIBUTE; }
@Test public void testGetWrappedRequest() { MockHttpServletRequest mock = new MockHttpServletRequest(); HttpServletRequest request = new HttpServletRequestWrapper(mock) {}; assertNotNull(ServletUtil.getWrappedRequest(request, MockHttpServletRequest.class)); assertNull(ServletUtil.getWrappedRequest(mock, request.getClass())); }
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, String> initParametersToMap(FilterConfig config); static T getWrappedRequest(ServletRequest request, Class<T> clazz); static boolean isMultipart(HttpServletRequest request); static boolean isForward(HttpServletRequest request); static boolean isInclude(HttpServletRequest request); static boolean isError(HttpServletRequest request); static DispatcherType getDispatcherType(HttpServletRequest request); static String getOriginalRequestURI(HttpServletRequest request); static String getOriginalRequestURLIncludingQueryString(HttpServletRequest request); static String getRequestUri(HttpServletRequest request); static final String FORWARD_REQUEST_URI_ATTRIBUTE; static final String FORWARD_QUERY_STRING_ATTRIBUTE; static final String INCLUDE_REQUEST_URI_ATTRIBUTE; static final String ERROR_REQUEST_STATUS_CODE_ATTRIBUTE; }
@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"); assertTrue(ServletUtil.isMultipart(mock)); mock.setContentType("text/html"); assertFalse(ServletUtil.isMultipart(mock)); }
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 config); static T getWrappedRequest(ServletRequest request, Class<T> clazz); static boolean isMultipart(HttpServletRequest request); static boolean isForward(HttpServletRequest request); static boolean isInclude(HttpServletRequest request); static boolean isError(HttpServletRequest request); static DispatcherType getDispatcherType(HttpServletRequest request); static String getOriginalRequestURI(HttpServletRequest request); static String getOriginalRequestURLIncludingQueryString(HttpServletRequest request); static String getRequestUri(HttpServletRequest request); static final String FORWARD_REQUEST_URI_ATTRIBUTE; static final String FORWARD_QUERY_STRING_ATTRIBUTE; static final String INCLUDE_REQUEST_URI_ATTRIBUTE; static final String ERROR_REQUEST_STATUS_CODE_ATTRIBUTE; }
@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, "/test.jsp"); assertFalse(ServletUtil.isForward(mock)); }
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 getWrappedRequest(ServletRequest request, Class<T> clazz); static boolean isMultipart(HttpServletRequest request); static boolean isForward(HttpServletRequest request); static boolean isInclude(HttpServletRequest request); static boolean isError(HttpServletRequest request); static DispatcherType getDispatcherType(HttpServletRequest request); static String getOriginalRequestURI(HttpServletRequest request); static String getOriginalRequestURLIncludingQueryString(HttpServletRequest request); static String getRequestUri(HttpServletRequest request); static final String FORWARD_REQUEST_URI_ATTRIBUTE; static final String FORWARD_QUERY_STRING_ATTRIBUTE; static final String INCLUDE_REQUEST_URI_ATTRIBUTE; static final String ERROR_REQUEST_STATUS_CODE_ATTRIBUTE; }
@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, "/test.jsp"); assertTrue(ServletUtil.isInclude(mock)); }
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 getWrappedRequest(ServletRequest request, Class<T> clazz); static boolean isMultipart(HttpServletRequest request); static boolean isForward(HttpServletRequest request); static boolean isInclude(HttpServletRequest request); static boolean isError(HttpServletRequest request); static DispatcherType getDispatcherType(HttpServletRequest request); static String getOriginalRequestURI(HttpServletRequest request); static String getOriginalRequestURLIncludingQueryString(HttpServletRequest request); static String getRequestUri(HttpServletRequest request); static final String FORWARD_REQUEST_URI_ATTRIBUTE; static final String FORWARD_QUERY_STRING_ATTRIBUTE; static final String INCLUDE_REQUEST_URI_ATTRIBUTE; static final String ERROR_REQUEST_STATUS_CODE_ATTRIBUTE; }
@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.isError(mock)); assertFalse(ServletUtil.isForward(mock)); assertFalse(ServletUtil.isInclude(mock)); mock.setAttribute(ServletUtil.FORWARD_REQUEST_URI_ATTRIBUTE, "/test.html"); assertTrue(ServletUtil.isError(mock)); assertTrue(ServletUtil.isForward(mock)); assertFalse(ServletUtil.isInclude(mock)); mock.setAttribute(ServletUtil.INCLUDE_REQUEST_URI_ATTRIBUTE, "/test.jsp"); assertTrue(ServletUtil.isError(mock)); assertFalse(ServletUtil.isForward(mock)); assertTrue(ServletUtil.isInclude(mock)); }
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(ERROR_REQUEST_STATUS_CODE_ATTRIBUTE) != null) { return DispatcherType.ERROR; } return DispatcherType.REQUEST; } static LinkedHashMap<String, String> initParametersToMap(ServletConfig config); static LinkedHashMap<String, String> initParametersToMap(FilterConfig config); static T getWrappedRequest(ServletRequest request, Class<T> clazz); static boolean isMultipart(HttpServletRequest request); static boolean isForward(HttpServletRequest request); static boolean isInclude(HttpServletRequest request); static boolean isError(HttpServletRequest request); static DispatcherType getDispatcherType(HttpServletRequest request); static String getOriginalRequestURI(HttpServletRequest request); static String getOriginalRequestURLIncludingQueryString(HttpServletRequest request); static String getRequestUri(HttpServletRequest request); static final String FORWARD_REQUEST_URI_ATTRIBUTE; static final String FORWARD_QUERY_STRING_ATTRIBUTE; static final String INCLUDE_REQUEST_URI_ATTRIBUTE; static final String ERROR_REQUEST_STATUS_CODE_ATTRIBUTE; }
@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.getDispatcherType(mock)); mock.setAttribute(ServletUtil.INCLUDE_REQUEST_URI_ATTRIBUTE, "/test.jsp"); assertEquals(DispatcherType.INCLUDE, ServletUtil.getDispatcherType(mock)); mock.removeAttribute(ServletUtil.INCLUDE_REQUEST_URI_ATTRIBUTE); mock.removeAttribute(ServletUtil.FORWARD_REQUEST_URI_ATTRIBUTE); mock.setAttribute(ServletUtil.ERROR_REQUEST_STATUS_CODE_ATTRIBUTE, 500); assertEquals(DispatcherType.ERROR, ServletUtil.getDispatcherType(mock)); mock.setAttribute(ServletUtil.FORWARD_REQUEST_URI_ATTRIBUTE, "/error.html"); assertEquals(DispatcherType.FORWARD, ServletUtil.getDispatcherType(mock)); mock.setAttribute(ServletUtil.INCLUDE_REQUEST_URI_ATTRIBUTE, "/error.jsp"); assertEquals(DispatcherType.INCLUDE, ServletUtil.getDispatcherType(mock)); }
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(ServletConfig config); static LinkedHashMap<String, String> initParametersToMap(FilterConfig config); static T getWrappedRequest(ServletRequest request, Class<T> clazz); static boolean isMultipart(HttpServletRequest request); static boolean isForward(HttpServletRequest request); static boolean isInclude(HttpServletRequest request); static boolean isError(HttpServletRequest request); static DispatcherType getDispatcherType(HttpServletRequest request); static String getOriginalRequestURI(HttpServletRequest request); static String getOriginalRequestURLIncludingQueryString(HttpServletRequest request); static String getRequestUri(HttpServletRequest request); static final String FORWARD_REQUEST_URI_ATTRIBUTE; static final String FORWARD_QUERY_STRING_ATTRIBUTE; static final String INCLUDE_REQUEST_URI_ATTRIBUTE; static final String ERROR_REQUEST_STATUS_CODE_ATTRIBUTE; }
@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()); mock.setRequestURI("/forwarded/to/test/path"); assertEquals("/some/path/and/some.file", ServletUtil.getOriginalRequestURI(mock)); }
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 content); List<Node> children(Node content); List<Node> children(Node content, String nodeTypeName); List<ContentMap> children(ContentMap content); List<ContentMap> children(ContentMap content, String nodeTypeName); ContentMap root(ContentMap contentMap); ContentMap root(ContentMap contentMap, String nodeTypeName); Node root(Node content); Node root(Node content, String nodeTypeName); ContentMap parent(ContentMap contentMap); ContentMap parent(ContentMap contentMap, String nodeTypeName); Node parent(Node content); Node parent(Node content, String nodeTypeName); ContentMap page(ContentMap content); Node page(Node content); List<ContentMap> ancestors(ContentMap contentMap); List<ContentMap> ancestors(ContentMap contentMap, String nodeTypeName); List<Node> ancestors(Node content); List<Node> ancestors(Node content, String nodeTypeName); Node inherit(Node content); Node inherit(Node content, String relPath); ContentMap inherit(ContentMap content); ContentMap inherit(ContentMap content, String relPath); Property inheritProperty(Node content, String relPath); Property inheritProperty(ContentMap content, String relPath); List<Node> inheritList(Node content, String relPath); List<ContentMap> inheritList(ContentMap content, String relPath); boolean isInherited(Node content); boolean isInherited(ContentMap content); boolean isFromCurrentPage(Node content); boolean isFromCurrentPage(ContentMap content); String link(String workspace, String nodeIdentifier); @Deprecated String link(Property property); String link(Node content); String link(ContentMap contentMap); String language(); String externalLink(Node content, String linkPropertyName); String externalLink(ContentMap content, String linkPropertyName); String externalLinkTitle(Node content, String linkPropertyName, String linkTitlePropertyName); String externalLinkTitle(ContentMap content, String linkPropertyName, String linkTitlePropertyName); boolean isEditMode(); boolean isPreviewMode(); boolean isAuthorInstance(); boolean isPublicInstance(); String createHtmlAttribute(String name, String value); SiblingsHelper siblings(Node node); SiblingsHelper siblings(ContentMap node); Node content(String path); Node content(String repository, String path); Node contentByIdentifier(String id); Node contentByIdentifier(String repository, String id); List<ContentMap> asContentMapList(Collection<Node> nodeList); List<Node> asNodeList(Collection<ContentMap> contentMapList); ContentMap decode(ContentMap content); Node decode(Node content); Node encode(Node content); String metaData(Node content, String property); String metaData(ContentMap content, String property); Collection<Node> search(String workspace, String statement, String language, String returnItemType); Collection<Node> simpleSearch(String workspace, String statement, String returnItemType, String startPath); }
@Test public void testPageFromRootShouldBeNull() throws RepositoryException { Node resultNode = functions.page(root); assertNull(resultNode); } @Test public void testPageHavingNoParentPageShouldBeNull() throws RepositoryException { Node componentWithoutPage = root.addNode("onlyComponent", NodeTypes.Component.NAME); Node resultNode = functions.page(componentWithoutPage); assertNull(resultNode); } @Test public void testPageFromNodeDepth1() throws RepositoryException { Node resultNode = functions.page(topPage); assertNodeEqualsNode(topPage, resultNode); } @Test public void testPageFromNodeDepth2() throws RepositoryException { Node resultNode = functions.page(childPage); assertNodeEqualsNode(childPage, resultNode); } @Test public void testPageFromComponentNodeDepth2() throws RepositoryException { Node resultNode = functions.page(childPageComponent); assertNodeEqualsNode(childPage, resultNode); } @Test public void testPageFromComponentNodeDepth3() throws RepositoryException { Node subSubComponent = childPageComponent.addNode("subSubCompoent", NodeTypes.Component.NAME); Node resultNode = functions.page(subSubComponent); assertNodeEqualsNode(childPage, resultNode); } @Test public void testPageContentMapFromRootShouldBeNull() throws RepositoryException { ContentMap resultNode = functions.page(rootContentMap); assertNull(resultNode); } @Test public void testPageContentMapHavingNoParentPageShouldBeNull() throws RepositoryException { Node componentWithoutPage = root.addNode("onlyComponent", NodeTypes.Component.NAME); ContentMap resultContentMap = functions.page(new ContentMap(componentWithoutPage)); assertNull(resultContentMap); } @Test public void testPageFromContentMapDepth1() throws RepositoryException { ContentMap resultContentMap = functions.page(topPageContentMap); assertMapEqualsMap(topPageContentMap, resultContentMap); } @Test public void testPageFromContentMapDepth2() throws RepositoryException { ContentMap resultContentMap = functions.page(childPageContentMap); assertMapEqualsMap(childPageContentMap, resultContentMap); } @Test public void testPageFromComponentContentMapDepth2() throws RepositoryException { ContentMap resultContentMap = functions.page(childPageComponentContentMap); assertMapEqualsMap(childPageContentMap, resultContentMap); } @Test public void testPageFromComponentContentMapDepth3() throws RepositoryException { Node subSubComponent = childPageComponent.addNode("subSubCompoent", NodeTypes.Component.NAME); ContentMap resultContentMap = functions.page(new ContentMap(subSubComponent)); assertMapEqualsMap(childPageContentMap, resultContentMap); }
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.getServerPort(); if ((scheme.equalsIgnoreCase("http") && port == 80) || (scheme.equalsIgnoreCase("https") && port == 443)) { } else { builder.append(":").append(port); } String requestUri = (String) request.getAttribute(FORWARD_REQUEST_URI_ATTRIBUTE); builder.append(requestUri); String queryString = (String) request.getAttribute(FORWARD_QUERY_STRING_ATTRIBUTE); if (StringUtils.isNotEmpty(queryString)) { builder.append("?").append(queryString); } return builder.toString(); } StringBuilder builder = new StringBuilder(); builder.append(request.getRequestURL()); String queryString = request.getQueryString(); if (StringUtils.isNotEmpty(queryString)) { builder.append("?").append(queryString); } return builder.toString(); } static LinkedHashMap<String, String> initParametersToMap(ServletConfig config); static LinkedHashMap<String, String> initParametersToMap(FilterConfig config); static T getWrappedRequest(ServletRequest request, Class<T> clazz); static boolean isMultipart(HttpServletRequest request); static boolean isForward(HttpServletRequest request); static boolean isInclude(HttpServletRequest request); static boolean isError(HttpServletRequest request); static DispatcherType getDispatcherType(HttpServletRequest request); static String getOriginalRequestURI(HttpServletRequest request); static String getOriginalRequestURLIncludingQueryString(HttpServletRequest request); static String getRequestUri(HttpServletRequest request); static final String FORWARD_REQUEST_URI_ATTRIBUTE; static final String FORWARD_QUERY_STRING_ATTRIBUTE; static final String INCLUDE_REQUEST_URI_ATTRIBUTE; static final String ERROR_REQUEST_STATUS_CODE_ATTRIBUTE; }
@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.getRequestURI()); mock.setAttribute(ServletUtil.FORWARD_QUERY_STRING_ATTRIBUTE, mock.getQueryString()); mock.setScheme("http"); mock.setServerName("some.domain"); mock.setServerPort(80); mock.setRequestURL("/forwarded/to/test/path"); mock.setQueryString("qwerty=yes"); assertEquals("http: mock.setServerPort(8080); assertEquals("http: }
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(delay, command); } DelayedExecutor(final Runnable command, long delay, long maxDelay); synchronized void trigger(); }
@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); } @Test public void testMultipleDelayedExecution() throws InterruptedException{ TestRunnable runnable = new TestRunnable(); DelayedExecutor executor = new DelayedExecutor(runnable, 100, 500); for(int i=0; i<5; i++){ executor.trigger(); Thread.sleep(10); } assertEquals(false, runnable.executed); Thread.sleep(100); assertEquals(true, runnable.executed); } @Test public void testExecutionAfterMaxDelay() throws InterruptedException{ TestRunnable runnable = new TestRunnable(); DelayedExecutor executor = new DelayedExecutor(runnable, 100, 200); for(int i=0; i<4; i++){ executor.trigger(); Thread.sleep(100); } 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 Content getWrappedContent(); @Override HierarchyManager getHierarchyManager(); @Override NodeData wrap(NodeData nodeData); }
@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"); hm.save(); Content plainContent = hm.getContent("/bla"); Content systemContent = new LazyContentWrapper(plainContent); NodeData nd = systemContent.getNodeData("nodeData2"); hm.getWorkspace().getSession().logout(); assertTrue(systemContent.getHierarchyManager().getWorkspace().getSession().isLive()); assertEquals(systemContent.getHierarchyManager(), LifeTimeJCRSessionUtil.getHierarchyManager("config")); assertEquals(systemContent.getHierarchyManager(), nd.getHierarchyManager()); } @Test public void testWrappingNDParent() throws Exception { HierarchyManager hm = MgnlContext.getInstance().getHierarchyManager("config"); assertNotSame(hm, LifeTimeJCRSessionUtil.getHierarchyManager("config")); hm.getRoot().createContent("bla", ItemType.CONTENT.getSystemName()).setNodeData("nodeData2", "boo"); hm.save(); Content plainContent = hm.getContent("/bla"); Content systemContent = new LazyContentWrapper(plainContent); NodeData nd = systemContent.getNodeData("nodeData2"); assertTrue(nd.getParent() instanceof LazyContentWrapper); } @Test public void testWrappingReferencedContent() throws Exception { HierarchyManager hm = MgnlContext.getInstance().getHierarchyManager("config"); assertNotSame(hm, LifeTimeJCRSessionUtil.getHierarchyManager("config")); hm.getRoot().createContent("bla", ItemType.CONTENT.getSystemName()).setNodeData("nodeData2", "/boo"); hm.getRoot().createContent("boo", ItemType.CONTENT.getSystemName()); hm.save(); Content plainContent = hm.getContent("/bla"); Content systemContent = new LazyContentWrapper(plainContent); Content referencedContent = systemContent.getNodeData("nodeData2").getReferencedContent(); assertTrue(referencedContent instanceof LazyContentWrapper); referencedContent = systemContent.getNodeData("nodeData2").getReferencedContent("config"); assertTrue(referencedContent instanceof LazyContentWrapper); }
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[] allowedTypes); Rule(String allowedTypes, String separator); void setAllowedTypes(String[] types); void addAllowType(String nodeType); void removeAllowType(String nodeType); boolean isAllowed(String nodeType); boolean isAllowed(Node node); @Override String toString(); void reverse(); }
@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 addAllowType(String nodeType); void removeAllowType(String nodeType); boolean isAllowed(String nodeType); boolean isAllowed(Node node); @Override String toString(); void reverse(); }
@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.isAllowed(node); Assert.assertTrue("Should be allowd", allowed); } @Test public void testIsNotAllowedNode() throws RepositoryException { Session session = MgnlContext.getJCRSession(RepositoryConstants.WEBSITE); Node node = session.getRootNode().addNode( "page", NodeTypes.Page.NAME); String allowedTypes = "mgnl:contentNode"; Rule rule = new Rule(allowedTypes, ","); boolean allowed = rule.isAllowed(node); Assert.assertTrue("Should be allowd", !allowed); }
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 (UnsupportedEncodingException e) { throw new RuntimeException(e); } } static String[] findResources(String regex); static String[] findResources(Filter filter); static InputStream getStream(String name); static InputStream getStream(String name, boolean cache); static URL getResource(String name); }
@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 sanitFile2 = ClasspathResourcesUtil.sanitizeToFile(u2); assertEquals(sanitFile1.getAbsolutePath(),sanitFile2.getAbsolutePath()); }
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 name); static Content getOrCreateContent(Content node, String name, ItemType contentType); static Content getOrCreateContent(Content node, String name, ItemType contentType, boolean save); static Content getCaseInsensitive(Content node, String name); static List<Content> collectAllChildren(Content node); static List<Content> collectAllChildren(Content node, ContentFilter filter); static List<Content> collectAllChildren(Content node, ItemType type); static Collection<Content> getAllChildren(Content node); static Collection<Content> getAllChildren(Content node, Comparator<Content> comp); static List<Content> collectAllChildren(Content node, ItemType[] types); static Content getAncestorOfType(final Content firstNode, final String nodeType); static void orderBefore(Content nodeToMove, String targetNodeName); static void orderAfter(Content nodeToMove, String targetNodeName); static void orderNodes(Content node, String[] nodes); static void orderNodes(Content node, Comparator<Content> comparator); static void visit(Content node, Visitor visitor); static void visit(Content node, Visitor visitor, ContentFilter filter); static Content createPath(HierarchyManager hm, String path); static Content createPath(HierarchyManager hm, String path, boolean save); static Content createPath(HierarchyManager hm, String path, ItemType type); static Content createPath(HierarchyManager hm, String path, ItemType type, boolean save); static Content createPath(Content parent, String path, ItemType type); static Content createPath(Content parent, String path, ItemType type, boolean save); static String uuid2path(String repository, String uuid); static String path2uuid(String repository, String path); static void deleteAndRemoveEmptyParents(Content node); static void deleteAndRemoveEmptyParents(Content node, int level); static void copyInSession(Content src, String dest); static void moveInSession(Content src, String dest); static void rename(Content node, String newName); static void changeNodeType(Content node, ItemType newType, boolean replaceAll); static Content asContent(Node content); static ContentFilter ALL_NODES_CONTENT_FILTER; static ContentFilter ALL_NODES_EXCEPT_JCR_CONTENT_FILTER; static ContentFilter EXCLUDE_META_DATA_CONTENT_FILTER; static ContentFilter MAGNOLIA_FILTER; }
@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 MockContent child2 = new MockContent("child2", bar); root.addContent(child2); final MockContent child2child = new MockContent("child2-child", foo); child2.addContent(child2child); final MockContent child3 = new MockContent("child3", foo); root.addContent(child3); final MockContent child3childFoo = new MockContent("child3-childFoo", foo); child3.addContent(child3childFoo); final MockContent child3childFoo2 = new MockContent("child3-childFoo2", foo); child3.addContent(child3childFoo2); final MockContent child3childFooChild = new MockContent("child3-childFoo-child", foo); child3childFoo.addContent(child3childFooChild); final MockContent child3childBar = new MockContent("child3-childBar", bar); child3.addContent(child3childBar); final MockContent child4 = new MockContent("child4", bar); root.addContent(child4); final MockContent child5 = new MockContent("child5", foo); root.addContent(child5); final ContentTypeRejector filter = new ContentTypeRejector("bar"); final ContentUtil.Visitor visitor = createStrictMock(ContentUtil.Visitor.class); visitor.visit(root); visitor.visit(child1); visitor.visit(child3); visitor.visit(child3childFoo); visitor.visit(child3childFooChild); visitor.visit(child3childFoo2); visitor.visit(child5); replay(visitor); ContentUtil.visit(root, visitor, filter); verify(visitor); }
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(readyToMove){ parent.orderBefore(nodeToMove.getName(), child.getName()); readyToMove = false; break; } if(child.getName().equals(targetNodeName)){ readyToMove = true; } } if(readyToMove){ for (Content child : children){ if(!nodeToMove.getName().equals(child.getName())){ parent.orderBefore(child.getName(), nodeToMove.getName()); } } } } static Content getContent(String repository, String path); static Content getContentByUUID(String repository, String uuid); static Content getContent(Content node, String name); static Content getOrCreateContent(Content node, String name, ItemType contentType); static Content getOrCreateContent(Content node, String name, ItemType contentType, boolean save); static Content getCaseInsensitive(Content node, String name); static List<Content> collectAllChildren(Content node); static List<Content> collectAllChildren(Content node, ContentFilter filter); static List<Content> collectAllChildren(Content node, ItemType type); static Collection<Content> getAllChildren(Content node); static Collection<Content> getAllChildren(Content node, Comparator<Content> comp); static List<Content> collectAllChildren(Content node, ItemType[] types); static Content getAncestorOfType(final Content firstNode, final String nodeType); static void orderBefore(Content nodeToMove, String targetNodeName); static void orderAfter(Content nodeToMove, String targetNodeName); static void orderNodes(Content node, String[] nodes); static void orderNodes(Content node, Comparator<Content> comparator); static void visit(Content node, Visitor visitor); static void visit(Content node, Visitor visitor, ContentFilter filter); static Content createPath(HierarchyManager hm, String path); static Content createPath(HierarchyManager hm, String path, boolean save); static Content createPath(HierarchyManager hm, String path, ItemType type); static Content createPath(HierarchyManager hm, String path, ItemType type, boolean save); static Content createPath(Content parent, String path, ItemType type); static Content createPath(Content parent, String path, ItemType type, boolean save); static String uuid2path(String repository, String uuid); static String path2uuid(String repository, String path); static void deleteAndRemoveEmptyParents(Content node); static void deleteAndRemoveEmptyParents(Content node, int level); static void copyInSession(Content src, String dest); static void moveInSession(Content src, String dest); static void rename(Content node, String newName); static void changeNodeType(Content node, ItemType newType, boolean replaceAll); static Content asContent(Node content); static ContentFilter ALL_NODES_CONTENT_FILTER; static ContentFilter ALL_NODES_EXCEPT_JCR_CONTENT_FILTER; static ContentFilter EXCLUDE_META_DATA_CONTENT_FILTER; static ContentFilter MAGNOLIA_FILTER; }
@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.getChildren(); CollectionUtils.transform(result, new Transformer() { @Override public Object transform(Object childObj) { return ((Content)childObj).getName(); } }); assertEquals(Arrays.asList(new String[]{"b", "a","c"}), result); }
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); static Content getOrCreateContent(Content node, String name, ItemType contentType); static Content getOrCreateContent(Content node, String name, ItemType contentType, boolean save); static Content getCaseInsensitive(Content node, String name); static List<Content> collectAllChildren(Content node); static List<Content> collectAllChildren(Content node, ContentFilter filter); static List<Content> collectAllChildren(Content node, ItemType type); static Collection<Content> getAllChildren(Content node); static Collection<Content> getAllChildren(Content node, Comparator<Content> comp); static List<Content> collectAllChildren(Content node, ItemType[] types); static Content getAncestorOfType(final Content firstNode, final String nodeType); static void orderBefore(Content nodeToMove, String targetNodeName); static void orderAfter(Content nodeToMove, String targetNodeName); static void orderNodes(Content node, String[] nodes); static void orderNodes(Content node, Comparator<Content> comparator); static void visit(Content node, Visitor visitor); static void visit(Content node, Visitor visitor, ContentFilter filter); static Content createPath(HierarchyManager hm, String path); static Content createPath(HierarchyManager hm, String path, boolean save); static Content createPath(HierarchyManager hm, String path, ItemType type); static Content createPath(HierarchyManager hm, String path, ItemType type, boolean save); static Content createPath(Content parent, String path, ItemType type); static Content createPath(Content parent, String path, ItemType type, boolean save); static String uuid2path(String repository, String uuid); static String path2uuid(String repository, String path); static void deleteAndRemoveEmptyParents(Content node); static void deleteAndRemoveEmptyParents(Content node, int level); static void copyInSession(Content src, String dest); static void moveInSession(Content src, String dest); static void rename(Content node, String newName); static void changeNodeType(Content node, ItemType newType, boolean replaceAll); static Content asContent(Node content); static ContentFilter ALL_NODES_CONTENT_FILTER; static ContentFilter ALL_NODES_EXCEPT_JCR_CONTENT_FILTER; static ContentFilter EXCLUDE_META_DATA_CONTENT_FILTER; static ContentFilter MAGNOLIA_FILTER; }
@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 DefaultContent); } @Test public void testAsContentReturnsNullIfNodeIsNull() throws Exception{ Node node = null; Content content = ContentUtil.asContent(node); assertNull(content); }
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); static String formatDate(Object val); static Date parseDateTime(String dateStr); static Date parseDate(String dateStr); static Calendar getLocalCalendarFromUTC(Calendar utc); static Calendar getUTCCalendarFromDialogString(String dateString); static Calendar getUTCCalendarFromLocalDate(Date date); static Calendar getCurrentUTCCalendar(); static String createDateExpression(Calendar calendar); static String createDateTimeExpression(Calendar calendar); static String createDateTimeExpressionIgnoreTimeZone(Calendar calendar); static final String FORMAT_DATE_SHORT; static final String FORMAT_DATE_MEDIUM; static final String FORMAT_DATE_LONG; static final String FORMAT_DATETIME_SHORT; static final String FORMAT_DATETIME_MEDIUM; static final String FORMAT_DATETIME_LONG; static final String FORMAT_TIME_SHORT; static final String FORMAT_TIME_MEDIUM; static final String FORMAT_TIME_LONG; static final String FORMAT_DEFAULTPATTERN; static final String YYYY_MM_DD; static final String YYYY_MM_DD_T_HH_MM_SS; static final TimeZone UTC_TIME_ZONE; }
@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\u00e4kuu 2008", DateUtil.format(getTestDate(), "EEEE, d. MMMM yyyy", new Locale("fi"))); }
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, EventListener listener); static void registerChangeListener(String workspace, String observationPath, boolean includeSubnodes, EventListener listener); static void registerChangeListener(String workspace, String observationPath, boolean includeSubnodes, String nodeType, EventListener listener); static void registerChangeListener(String workspace, String observationPath, boolean includeSubnodes, String nodeType, int eventTypesMask, EventListener listener); static void registerChangeListener(String workspace, String observationPath, boolean includeSubnodes, String[] nodeTypes, EventListener listener); static void registerChangeListener(String workspace, String observationPath, boolean includeSubnodes, String[] nodeTypes, int eventTypesMask, EventListener listener); static void registerDeferredChangeListener(String workspace, String observationPath, EventListener listener, long delay, long maxDelay); static void registerDeferredChangeListener(String workspace, String observationPath, boolean includeSubnodes, EventListener listener, long delay, long maxDelay); static void registerDeferredChangeListener(String workspace, String observationPath, boolean includeSubnodes, String nodeType, EventListener listener, long delay, long maxDelay); static void registerDeferredChangeListener(String workspace, String observationPath, boolean includeSubnodes, String[] nodeTypes, EventListener listener, long delay, long maxDelay); static EventListener instanciateDeferredEventListener(EventListener listener, long delay, long maxDelay); static void unregisterChangeListener(String workspace, EventListener listener); }
@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 e) { assertEquals("Observation manager can't be obtained due to invalid session.", e.getMessage()); } } @Test public void testRegisterWhenSessionValid() throws Exception { MockSession session = setupMockSession(true); ObservationManager observationManager = setupMockObservationManager(session); EventListener listener = new EventListener() { @Override public void onEvent(EventIterator events) { } }; ObservationUtil.registerChangeListener("some-repo", "/parent", listener); verify(observationManager).addEventListener(listener, 63, "/parent", true, null, null, false); }
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 [" + listener + "] from workspace " + workspace, e); } } static void dispose(String workspace); static void registerChangeListener(String workspace, String observationPath, EventListener listener); static void registerChangeListener(String workspace, String observationPath, boolean includeSubnodes, EventListener listener); static void registerChangeListener(String workspace, String observationPath, boolean includeSubnodes, String nodeType, EventListener listener); static void registerChangeListener(String workspace, String observationPath, boolean includeSubnodes, String nodeType, int eventTypesMask, EventListener listener); static void registerChangeListener(String workspace, String observationPath, boolean includeSubnodes, String[] nodeTypes, EventListener listener); static void registerChangeListener(String workspace, String observationPath, boolean includeSubnodes, String[] nodeTypes, int eventTypesMask, EventListener listener); static void registerDeferredChangeListener(String workspace, String observationPath, EventListener listener, long delay, long maxDelay); static void registerDeferredChangeListener(String workspace, String observationPath, boolean includeSubnodes, EventListener listener, long delay, long maxDelay); static void registerDeferredChangeListener(String workspace, String observationPath, boolean includeSubnodes, String nodeType, EventListener listener, long delay, long maxDelay); static void registerDeferredChangeListener(String workspace, String observationPath, boolean includeSubnodes, String[] nodeTypes, EventListener listener, long delay, long maxDelay); static EventListener instanciateDeferredEventListener(EventListener listener, long delay, long maxDelay); static void unregisterChangeListener(String workspace, EventListener listener); }
@Test public void testDontFailUnregisterWhenSessionInvalid() throws Exception { MockSession session = setupMockSession(false); ObservationManager observationManager = setupMockObservationManager(session); EventListener listener = new EventListener() { @Override public void onEvent(EventIterator events) { } }; ObservationUtil.unregisterChangeListener("some-repo", listener); verify(observationManager, times(0)).removeEventListener(listener); } @Test public void testUnregisterWhenSessionValid() throws Exception { MockSession session = setupMockSession(true); ObservationManager observationManager = setupMockObservationManager(session); EventListener listener = new EventListener() { @Override public void onEvent(EventIterator events) { } }; ObservationUtil.unregisterChangeListener("some-repo", listener); verify(observationManager).removeEventListener(listener); }
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 testNormalizingNFDStringMakesItEqualsToNFCStringWithAutoDetect() { assertEquals(NFC, UnicodeNormalizer.normalizeNFC(NFD)); } @Test public void testNormalizationAlsoWorksForStringsThatWereOriginallyNotUTF8WithAutoDetect() { assertEquals(MACROMAN, NFC); assertEquals(NFC, UnicodeNormalizer.normalizeNFC(MACROMAN)); } @Test public void testNonNormalizer() { final UnicodeNormalizer.Normalizer n = new UnicodeNormalizer.NonNormalizer(); assertEquals(NFD, n.normalizeNFC(NFD)); assertEquals(NFC, n.normalizeNFC(MACROMAN)); assertEquals("hello", n.normalizeNFC("hello")); } @Test public void testJava6Normalizer() { final UnicodeNormalizer.Normalizer n = new UnicodeNormalizer.Java6Normalizer(); assertEquals(NFC, n.normalizeNFC(NFD)); assertEquals(NFC, n.normalizeNFC(MACROMAN)); assertEquals("hello", n.normalizeNFC("hello")); }
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 getPatternString(); void setPatternString(String patternString); @Override String toString(); static final String URL_CHAR_PATTERN; static final String MULTIPLE_CHAR_PATTERN; static final String SINGLE_CHAR_PATTERN; }
@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 testNoWildcardsNoMatch() { assertFalse(new SimpleUrlPattern("/test/url.html").match("/test/secondurl.html")); } @Test public void testStarMatch() { assertTrue(new SimpleUrlPattern("/test/*.html").match("/test/url.html")); } @Test public void testStarNoMatch() { assertFalse(new SimpleUrlPattern("/test/*.html").match("/other/url.html")); } @Test public void testStarMatch2() { assertTrue(new SimpleUrlPattern("/*/*.html").match("/test/url.html")); } @Test public void testStarNoMatch2() { assertFalse(new SimpleUrlPattern("/*/*.html").match("/test/url.jsp")); } @Test public void testStarMatch3() { assertTrue(new SimpleUrlPattern("*.html").match("/test/url.html")); } @Test public void testStarNoMatch3() { assertFalse(new SimpleUrlPattern("*.html").match("/test/url.jsp")); } @Test public void testStarMatch4() { assertTrue(new SimpleUrlPattern("*.html").match("/test/dir/dir/url.html")); } @Test public void testStarNoMatch4() { assertFalse(new SimpleUrlPattern("*.html").match("/test/dir/dir/url.jsp")); } @Test public void testQuestionMarkMatch() { assertTrue(new SimpleUrlPattern("/test/num?page.html").match("/test/num2page.html")); } @Test public void testWildcardsMatch() { assertTrue(new SimpleUrlPattern("num2page.html")); } @Test public void testWildcardsWithSpecialChars() { assertTrue(new SimpleUrlPattern("page‘.html")); } @Test public void testWildcardsWithNewline() { assertTrue(new SimpleUrlPattern("/*").match("/page\nxxx\nbbb.html")); } @Test public void testGroupMatch() { assertTrue(new SimpleUrlPattern("/[a,b]/num/*").match("/b/num/blah")); } @Test public void testEncodedMatch() { assertTrue(new SimpleUrlPattern("/*").match("/magnoliaAuthor/dms/M--ller_PP-Praesentation/M%E2%94%9C%E2%95%9Dller_PP-Praesentation.doc")); assertTrue(new SimpleUrlPattern("/*").match("/dms/M--ller_PP-Praesentation/M\u00FCller_PP-Praesentation.doc")); assertTrue(new SimpleUrlPattern("/*").match(NFC)); assertTrue(new SimpleUrlPattern("/*").match(NFD)); assertTrue(new SimpleUrlPattern("/*").match(MACROMAN)); assertTrue(new SimpleUrlPattern("/*").match("/£")); } @Test public void testWildcardsWithUrlContainingDots() throws Exception { SimpleUrlPattern sup = new SimpleUrlPattern("*.html").match("/test.foo/dir.bar/dir.baz/url.html")); }
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); static String getFolder(String path); static String getFileName(String path); static String getExtension(String path); static String stripExtension(String path); }
@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.createPath("/foo", "bar/zed")); assertEquals("/foo assertEquals("/foo } @Test(expected = NullPointerException.class) public void testCreatePathDoesNotSupportNullArgument() { PathUtil.createPath(null, null); }
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 getExtension(String path); static String stripExtension(String path); }
@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 testAddLeadingSlashDoesNotSupportNullArgument() { PathUtil.addLeadingSlash(null); }
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); static String getFileName(String path); static String getExtension(String path); static String stripExtension(String path); }
@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("foobar")); assertEquals("foo", PathUtil.getFolder("foo/")); assertEquals("foo/bar", PathUtil.getFolder("foo/bar/")); assertEquals("/foo/bar", PathUtil.getFolder("/foo/bar/")); }
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(String path); static String getExtension(String path); static String stripExtension(String path); }
@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("", PathUtil.getFileName("foo/bar/")); } @Test(expected = NullPointerException.class) public void testGetFileNameDoesNotSupportNullArgument() { PathUtil.getFileName(null); }
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 getFileName(String path); static String getExtension(String path); static String stripExtension(String path); }
@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("")); assertEquals("", PathUtil.getExtension("/")); assertEquals(null, PathUtil.getExtension(null)); }
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(String path); static String stripExtension(String path); }
@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("", PathUtil.stripExtension("")); assertEquals("/", PathUtil.stripExtension("/")); assertEquals(null, PathUtil.stripExtension(null)); }
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(fileName)); String dataRow = jaasConfig.readLine(); while (dataRow != null) { names.add(dataRow); dataRow = jaasConfig.readLine(); } } catch (IOException e) { throw new RuntimeException(e); } finally { try { if (jaasConfig != null) { jaasConfig.close(); } } catch (IOException e) { throw new RuntimeException(e); } } return names; } static List<String> getTrimmedLinesMatching(String fileName, String regExp); static List<String> getLines(String fileName); }
@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!"); } catch (Throwable t) { assertTrue(t.getCause() instanceof FileNotFoundException); } }
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 = iterator.next().trim(); if (currentLine.matches(regExp)) { matchingLines.add(currentLine); } } return matchingLines; } static List<String> getTrimmedLinesMatching(String fileName, String regExp); static List<String> getLines(String fileName); }
@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 = TextFileUtil.getTrimmedLinesMatching("src/test/resources/config/current-jaas.config", "^Jackrabbit.*"); assertTrue(result.isEmpty()); }
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, toBoolean("on", false)); assertEquals(false, toBoolean("off", true)); assertEquals(false, toBoolean("off", false)); assertEquals(true, toBoolean("yes", true)); assertEquals(true, toBoolean("yes", false)); assertEquals(false, toBoolean("no", true)); assertEquals(false, toBoolean("no", false)); } @Test public void testToBooleanHandlesNullsAndEmptyStringsGracefully() { assertEquals(true, toBoolean(null, true)); assertEquals(false, toBoolean(null, false)); assertEquals(true, toBoolean("", true)); assertEquals(false, toBoolean("", false)); } @Test public void testToBooleanUsesDefaultValueForUnknownValues() { assertEquals(true, toBoolean("blah", true)); assertEquals(false, toBoolean("blah", false)); }
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.addContent(d); final NodePathComparator comparator = new NodePathComparator(); assertEquals(0, comparator.compare(b ,otherB)); assertTrue(comparator.compare(a, b) < 0); assertTrue(comparator.compare(b, a) > 0); assertTrue(comparator.compare(d, a) > 0); assertTrue(comparator.compare(b, d) < 0); }
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 void addGroup(String groupName); @Override void removeRole(String roleName); @Override void removeGroup(String groupName); @Override boolean hasRole(String roleName); @Override String getProperty(String propertyName); @Override void setProperty(String propertyName, String value); @Override Collection<String> getRoles(); @Override Collection<String> getGroups(); @Override Collection<String> getAllGroups(); @Override String getId(); }
@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.size()); } @Test public void testGetRolesWithoutDuplicates() throws AccessDeniedException { final Collection rolesB = gman.getGroup("groupB").getRoles(); assertEquals(2, rolesB.size()); assertTrue(rolesB.contains("roleX")); assertTrue(rolesB.contains("roleW")); final Collection rolesC = gman.getGroup("groupC").getRoles(); assertEquals(0, rolesC.size()); }
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); @Override void removeRole(String roleName); @Override void removeGroup(String groupName); @Override boolean hasRole(String roleName); @Override String getProperty(String propertyName); @Override void setProperty(String propertyName, String value); @Override Collection<String> getRoles(); @Override Collection<String> getGroups(); @Override Collection<String> getAllGroups(); @Override String getId(); }
@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()); } @Test public void testGetGroupsReturnsDirectGroupsWithoutDuplicates() throws AccessDeniedException { final Collection groupsB = gman.getGroup("groupB").getGroups(); assertEquals(2, groupsB.size()); assertTrue(groupsB.contains("groupA")); assertTrue(groupsB.contains("groupC")); }
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(String roleName); @Override void addGroup(String groupName); @Override void removeRole(String roleName); @Override void removeGroup(String groupName); @Override boolean hasRole(String roleName); @Override String getProperty(String propertyName); @Override void setProperty(String propertyName, String value); @Override Collection<String> getRoles(); @Override Collection<String> getGroups(); @Override Collection<String> getAllGroups(); @Override String getId(); }
@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 Collection<String> groupsD= gman.getAllGroups("groupD"); assertEquals(0, groupsD.size()); }
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 boolean granted = PermissionUtil.isGranted(repositoryName, handle, Session.ACTION_READ); if (!granted) { final int statusCode = SecurityUtil.isAnonymous() ? HttpServletResponse.SC_UNAUTHORIZED : HttpServletResponse.SC_FORBIDDEN; response.setStatus(statusCode); } return granted; } @Override boolean isAllowed(HttpServletRequest request, HttpServletResponse response); }
@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); assertEquals(false, result); verify(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED); } @Test public void testIsAllowedForOther() throws Exception { when(MgnlContext.getUser().getName()).thenReturn("AnyAuthenticatedUser"); when(request.getMethod()).thenReturn("GET"); final ContentSecurityFilter filter = new ContentSecurityFilter(); final boolean result = filter.isAllowed(request, response); assertEquals(false, result); verify(response).setStatus(HttpServletResponse.SC_FORBIDDEN); }
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(HttpServletResponse.SC_FORBIDDEN); return false; } if (Lock.isSystemLocked()) { response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); return false; } final boolean authorized = isAuthorized(request); if (!authorized) { final int statusCode = SecurityUtil.isAnonymous() ? HttpServletResponse.SC_UNAUTHORIZED : HttpServletResponse.SC_FORBIDDEN; response.setStatus(statusCode); } return authorized; } @Override boolean isAllowed(HttpServletRequest request, HttpServletResponse response); static final String URI_REPOSITORY; static final String URI_WORKSPACE; }
@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(false, result); verify(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED); } @Test public void testIsAllowedForOther() throws Exception { when(MgnlContext.getUser().getName()).thenReturn("AnyAuthenticatedUser"); when(request.getMethod()).thenReturn("GET"); final URISecurityFilter filter = new URISecurityFilter(); final boolean result = filter.isAllowed(request, response); assertEquals(false, result); verify(response).setStatus(HttpServletResponse.SC_FORBIDDEN); }
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; } else if (Session.ACTION_REMOVE.equals(perm)) { oldPerms += Permission.REMOVE; } else if (Session.ACTION_SET_PROPERTY.equals(perm)) { oldPerms += Permission.SET; } } return oldPerms; } static AccessManager getAccessManager(String workspace, Subject subject); static boolean isGranted(Node node, long requiredPermissions); static boolean isGranted(String workspace, String path, String requiredPermissions); static boolean isGranted(Session jcrSession, String path, long oldPermissions); static boolean isGranted(Session jcrSession, String path, String action); static void verifyIsGrantedOrThrowException(Session jcrSession, String path, String action); }
@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)); assertEquals(Session.ACTION_SET_PROPERTY, PermissionUtil.convertPermissions(Permission.SET)); assertEquals("add_node,read,remove,set_property", PermissionUtil.convertPermissions(Permission.ALL)); assertEquals("read,set_property", PermissionUtil.convertPermissions(Permission.READ | Permission.SET)); } @Test public void testFailsOnCustomPermissions() { try { final String result = PermissionUtil.convertPermissions(64); fail("Should have failed - but returned ["+result+"] instead."); } catch (IllegalArgumentException e) { assertEquals("Unknown permissions: 64", e.getMessage()); } } @Test public void testSuccessOnCustomPermissionAndNormalPermission() { final String result = PermissionUtil.convertPermissions(64 | Permission.READ); assertEquals("read", result); }
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 workspace, Subject subject); static boolean isGranted(Node node, long requiredPermissions); static boolean isGranted(String workspace, String path, String requiredPermissions); static boolean isGranted(Session jcrSession, String path, long oldPermissions); static boolean isGranted(Session jcrSession, String path, String action); static void verifyIsGrantedOrThrowException(Session jcrSession, String path, String action); }
@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, Collection<String> groups, Collection<String> roles, Map<String, String> properties, String path, String uuid); @Override boolean inGroup(String groupName); @Override void removeGroup(String groupName); @Override void addGroup(String groupName); @Override boolean isEnabled(); @Override @Deprecated void setEnabled(boolean enabled); @Override boolean hasRole(String roleName); @Override void removeRole(String roleName); @Override void addRole(String roleName); int getFailedLoginAttempts(); Calendar getReleaseTime(); @Override String getName(); @Override String getPassword(); @Override String getLanguage(); @Override String getProperty(String propertyName); @Override Collection<String> getGroups(); @Override Collection<String> getAllGroups(); @Override Collection<String> getRoles(); @Override Collection<String> getAllRoles(); String getPath(); @Deprecated void setPath(String path); String getRealm(); @Deprecated void setLastAccess(); @Deprecated Content getUserNode(); @Override @Deprecated void setProperty(String propertyName, String value); @Override String getIdentifier(); @Deprecated String getUuid(); @Override String toString(); }
@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("georges").getGroups(); assertEquals(2, groups.size()); assertTrue(groups.contains("groupA")); assertTrue(groups.contains("groupB")); }
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 = SecuritySupport.Factory.getInstance().getGroupManager(); addSubgroups(allGroups, man, groups); allGroups.addAll(groups); return allGroups; } MgnlUser(String name, String realm, Collection<String> groups, Collection<String> roles, Map<String, String> properties); MgnlUser(String name, String realm, Collection<String> groups, Collection<String> roles, Map<String, String> properties, String path, String uuid); @Override boolean inGroup(String groupName); @Override void removeGroup(String groupName); @Override void addGroup(String groupName); @Override boolean isEnabled(); @Override @Deprecated void setEnabled(boolean enabled); @Override boolean hasRole(String roleName); @Override void removeRole(String roleName); @Override void addRole(String roleName); int getFailedLoginAttempts(); Calendar getReleaseTime(); @Override String getName(); @Override String getPassword(); @Override String getLanguage(); @Override String getProperty(String propertyName); @Override Collection<String> getGroups(); @Override Collection<String> getAllGroups(); @Override Collection<String> getRoles(); @Override Collection<String> getAllRoles(); String getPath(); @Deprecated void setPath(String path); String getRealm(); @Deprecated void setLastAccess(); @Deprecated Content getUserNode(); @Override @Deprecated void setProperty(String propertyName, String value); @Override String getIdentifier(); @Deprecated String getUuid(); @Override String toString(); }
@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("groupD")); }
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, Collection<String> groups, Collection<String> roles, Map<String, String> properties, String path, String uuid); @Override boolean inGroup(String groupName); @Override void removeGroup(String groupName); @Override void addGroup(String groupName); @Override boolean isEnabled(); @Override @Deprecated void setEnabled(boolean enabled); @Override boolean hasRole(String roleName); @Override void removeRole(String roleName); @Override void addRole(String roleName); int getFailedLoginAttempts(); Calendar getReleaseTime(); @Override String getName(); @Override String getPassword(); @Override String getLanguage(); @Override String getProperty(String propertyName); @Override Collection<String> getGroups(); @Override Collection<String> getAllGroups(); @Override Collection<String> getRoles(); @Override Collection<String> getAllRoles(); String getPath(); @Deprecated void setPath(String path); String getRealm(); @Deprecated void setLastAccess(); @Deprecated Content getUserNode(); @Override @Deprecated void setProperty(String propertyName, String value); @Override String getIdentifier(); @Deprecated String getUuid(); @Override String toString(); }
@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 testGetRolesReturnsDirectRolesWithoutDuplicates() { final Collection<String> roles = uman.getUser("julien").getRoles(); assertEquals(2, roles.size()); assertTrue(roles.contains("roleY")); assertTrue(roles.contains("roleX")); }
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<String> allGroups = getAllGroups(); GroupManager man = SecuritySupport.Factory.getInstance().getGroupManager(); for (String group : allGroups) { try { allRoles.addAll(man.getGroup(group).getRoles()); } catch (AccessDeniedException e) { log.debug("Skipping denied group " + group + " for user " + getName(), e); } catch (UnsupportedOperationException e) { log.debug("Skipping unsupported getGroup() for group " + group + " and user " + getName(), e); } } return allRoles; } MgnlUser(String name, String realm, Collection<String> groups, Collection<String> roles, Map<String, String> properties); MgnlUser(String name, String realm, Collection<String> groups, Collection<String> roles, Map<String, String> properties, String path, String uuid); @Override boolean inGroup(String groupName); @Override void removeGroup(String groupName); @Override void addGroup(String groupName); @Override boolean isEnabled(); @Override @Deprecated void setEnabled(boolean enabled); @Override boolean hasRole(String roleName); @Override void removeRole(String roleName); @Override void addRole(String roleName); int getFailedLoginAttempts(); Calendar getReleaseTime(); @Override String getName(); @Override String getPassword(); @Override String getLanguage(); @Override String getProperty(String propertyName); @Override Collection<String> getGroups(); @Override Collection<String> getAllGroups(); @Override Collection<String> getRoles(); @Override Collection<String> getAllRoles(); String getPath(); @Deprecated void setPath(String path); String getRealm(); @Deprecated void setLastAccess(); @Deprecated Content getUserNode(); @Override @Deprecated void setProperty(String propertyName, String value); @Override String getIdentifier(); @Deprecated String getUuid(); @Override String toString(); }
@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")); assertTrue(rolesG.contains("roleY")); assertTrue(rolesG.contains("roleZ")); final Collection<String> rolesJ = uman.getUser("julien").getAllRoles(); assertEquals(3, rolesJ.size()); assertTrue(rolesJ.contains("roleX")); assertTrue(rolesJ.contains("roleY")); assertTrue(rolesJ.contains("roleZ")); }
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); MgnlUser(String name, String realm, Collection<String> groups, Collection<String> roles, Map<String, String> properties, String path, String uuid); @Override boolean inGroup(String groupName); @Override void removeGroup(String groupName); @Override void addGroup(String groupName); @Override boolean isEnabled(); @Override @Deprecated void setEnabled(boolean enabled); @Override boolean hasRole(String roleName); @Override void removeRole(String roleName); @Override void addRole(String roleName); int getFailedLoginAttempts(); Calendar getReleaseTime(); @Override String getName(); @Override String getPassword(); @Override String getLanguage(); @Override String getProperty(String propertyName); @Override Collection<String> getGroups(); @Override Collection<String> getAllGroups(); @Override Collection<String> getRoles(); @Override Collection<String> getAllRoles(); String getPath(); @Deprecated void setPath(String path); String getRealm(); @Deprecated void setLastAccess(); @Deprecated Content getUserNode(); @Override @Deprecated void setProperty(String propertyName, String value); @Override String getIdentifier(); @Deprecated String getUuid(); @Override String toString(); }
@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> principals, String name); static ACL findAccessControlList(Subject subject, String name); static T removePrincipal(Iterable<Principal> principals, Class<T> clazz); }
@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 Subject(); User user = mock(User.class); PrincipalCollectionImpl collection = new PrincipalCollectionImpl(); collection.add(user); subject.getPrincipals().add(collection); assertSame(user, PrincipalUtil.findPrincipal(subject, User.class)); }
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, String name); static ACL findAccessControlList(Subject subject, String name); static T removePrincipal(Iterable<Principal> principals, Class<T> clazz); }
@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.findAccessControlList(subject, "website")); assertSame(acl, PrincipalUtil.findAccessControlList(subject.getPrincipals(), "website")); }
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<Principal> principals, String name); static ACL findAccessControlList(Subject subject, String name); static T removePrincipal(Iterable<Principal> principals, Class<T> clazz); }
@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 testRemovePrincipalFromCollection() throws Exception { Subject subject = new Subject(); User user = mock(User.class); PrincipalCollectionImpl collection = new PrincipalCollectionImpl(); collection.add(user); subject.getPrincipals().add(collection); assertSame(user, PrincipalUtil.removePrincipal(subject.getPrincipals(), User.class)); assertFalse(collection.contains(user)); }
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() { assertEquals("/public/c/ca", hm.getParentPath("Casimir")); assertEquals("/public/c/ca", hm.getParentPath("CASIMIR")); }
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 getMaxFailedLoginAttempts(); @Override int getLockTimePeriod(); @Override void setLockTimePeriod(int lockTimePeriod); @Override User setProperty(final User user, final String propertyName, final Value propertyValue); @Override User setProperty(final User user, final String propertyName, final String propertyValue); @Deprecated String getName(); @Deprecated void setName(String name); void setRealmName(String name); String getRealmName(); void setAllowCrossRealmDuplicateNames(boolean allowCrossRealmDuplicateNames); boolean isAllowCrossRealmDuplicateNames(); @Override User getUser(final String name); @Override User getUserById(final String id); @Override User getUser(Subject subject); @Override User getSystemUser(); @Override User getAnonymousUser(); @Override Collection<User> getAllUsers(); void updateUserListWithAllChildren(Node node, Collection<User> users); @Override User createUser(final String name, final String pw); @Override User createUser(final String path, final String name, final String pw); @Override User changePassword(final User user, final String newPassword); @Override void updateLastAccessTimestamp(final User user); @Override Map<String, ACL> getACLs(final User user); @Override User addRole(User user, String roleName); @Override User addGroup(User user, String groupName); @Override User removeGroup(User user, String groupName); @Override User removeRole(User user, String roleName); static final String PROPERTY_EMAIL; static final String PROPERTY_LANGUAGE; static final String PROPERTY_LASTACCESS; static final String PROPERTY_PASSWORD; static final String PROPERTY_TITLE; static final String PROPERTY_ENABLED; static final String NODE_ACLUSERS; }
@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(justCheckingIfValidateUsernameIsCalledMessage); } }; try { hm.createUser("bleh", "blah"); fail("should have failed"); } catch (IllegalArgumentException e) { assertEquals(justCheckingIfValidateUsernameIsCalledMessage, e.getMessage()); } }
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 { user = Security.getUserManager().getUser(name); } if (user != null) { throw new IllegalArgumentException("User with name " + name + " already exists."); } } MgnlUserManager(); @Override void setMaxFailedLoginAttempts(int maxFailedLoginAttempts); @Override int getMaxFailedLoginAttempts(); @Override int getLockTimePeriod(); @Override void setLockTimePeriod(int lockTimePeriod); @Override User setProperty(final User user, final String propertyName, final Value propertyValue); @Override User setProperty(final User user, final String propertyName, final String propertyValue); @Deprecated String getName(); @Deprecated void setName(String name); void setRealmName(String name); String getRealmName(); void setAllowCrossRealmDuplicateNames(boolean allowCrossRealmDuplicateNames); boolean isAllowCrossRealmDuplicateNames(); @Override User getUser(final String name); @Override User getUserById(final String id); @Override User getUser(Subject subject); @Override User getSystemUser(); @Override User getAnonymousUser(); @Override Collection<User> getAllUsers(); void updateUserListWithAllChildren(Node node, Collection<User> users); @Override User createUser(final String name, final String pw); @Override User createUser(final String path, final String name, final String pw); @Override User changePassword(final User user, final String newPassword); @Override void updateLastAccessTimestamp(final User user); @Override Map<String, ACL> getACLs(final User user); @Override User addRole(User user, String roleName); @Override User addGroup(User user, String groupName); @Override User removeGroup(User user, String groupName); @Override User removeRole(User user, String roleName); static final String PROPERTY_EMAIL; static final String PROPERTY_LANGUAGE; static final String PROPERTY_LASTACCESS; static final String PROPERTY_PASSWORD; static final String PROPERTY_TITLE; static final String PROPERTY_ENABLED; static final String NODE_ACLUSERS; }
@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().validateUsername(""); fail("should have failed"); } catch (IllegalArgumentException e) { assertEquals(" is not a valid username.", e.getMessage()); } } @Test public void testUsernameCantBeBlank() { try { new MgnlUserManager().validateUsername(" "); fail("should have failed"); } catch (IllegalArgumentException e) { assertEquals(" is not a valid username.", e.getMessage()); } }
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() = '" + name + "'"; } else { where = "where name() = '" + name + "' and isdescendantnode(['/" + realmName + "'])"; } final String statement = "select * from [" + NodeTypes.User.NAME + "] " + where; Query query = session.getWorkspace().getQueryManager().createQuery(statement, Query.JCR_SQL2); NodeIterator iter = query.execute().getNodes(); Node user = null; while (iter.hasNext()) { Node node = iter.nextNode(); if (node.isNodeType(NodeTypes.User.NAME)) { user = node; break; } } if (iter.hasNext()) { log.error("More than one user found with name [{}] in realm [{}]", name, realmName); } return user; } MgnlUserManager(); @Override void setMaxFailedLoginAttempts(int maxFailedLoginAttempts); @Override int getMaxFailedLoginAttempts(); @Override int getLockTimePeriod(); @Override void setLockTimePeriod(int lockTimePeriod); @Override User setProperty(final User user, final String propertyName, final Value propertyValue); @Override User setProperty(final User user, final String propertyName, final String propertyValue); @Deprecated String getName(); @Deprecated void setName(String name); void setRealmName(String name); String getRealmName(); void setAllowCrossRealmDuplicateNames(boolean allowCrossRealmDuplicateNames); boolean isAllowCrossRealmDuplicateNames(); @Override User getUser(final String name); @Override User getUserById(final String id); @Override User getUser(Subject subject); @Override User getSystemUser(); @Override User getAnonymousUser(); @Override Collection<User> getAllUsers(); void updateUserListWithAllChildren(Node node, Collection<User> users); @Override User createUser(final String name, final String pw); @Override User createUser(final String path, final String name, final String pw); @Override User changePassword(final User user, final String newPassword); @Override void updateLastAccessTimestamp(final User user); @Override Map<String, ACL> getACLs(final User user); @Override User addRole(User user, String roleName); @Override User addGroup(User user, String groupName); @Override User removeGroup(User user, String groupName); @Override User removeRole(User user, String roleName); static final String PROPERTY_EMAIL; static final String PROPERTY_LANGUAGE; static final String PROPERTY_LASTACCESS; static final String PROPERTY_PASSWORD; static final String PROPERTY_TITLE; static final String PROPERTY_ENABLED; static final String NODE_ACLUSERS; }
@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 NodeIterator nodeIterator = mock(NodeIterator.class); final Node node = mock(Node.class); when(session.getWorkspace()).thenReturn(workspace); when(workspace.getQueryManager()).thenReturn(qm); when(qm.createQuery("select * from [mgnl:user] where name() = 'test'", Query.JCR_SQL2)).thenReturn(query); when(query.execute()).thenReturn(result); when(result.getNodes()).thenReturn(nodeIterator); when(nodeIterator.hasNext()).thenReturn(true).thenReturn(false); when(nodeIterator.nextNode()).thenReturn(node); when(node.isNodeType(NodeTypes.User.NAME)).thenReturn(true); MgnlUserManager um = new MgnlUserManager(); um.setRealmName(Realm.REALM_ALL.getName()); final Node principal = um.findPrincipalNode("test", session); assertNotNull(principal); }
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) throws RepositoryException { String path = ((MgnlUser) user).getPath(); Node userNode; try { userNode = session.getNode(path); if(propertyValue != null || PropertyUtil.getPropertyOrNull(userNode, propertyName) != null){ if(StringUtils.equals(propertyName, PROPERTY_PASSWORD)){ setPasswordProperty(userNode, propertyValue.getString()); } else{ userNode.setProperty(propertyName, propertyValue); session.save(); } } } catch (RepositoryException e) { session.refresh(false); log.error("Property {} can't be changed. " + e.getMessage(), propertyName); return user; } return newUserInstance(userNode); } }); } MgnlUserManager(); @Override void setMaxFailedLoginAttempts(int maxFailedLoginAttempts); @Override int getMaxFailedLoginAttempts(); @Override int getLockTimePeriod(); @Override void setLockTimePeriod(int lockTimePeriod); @Override User setProperty(final User user, final String propertyName, final Value propertyValue); @Override User setProperty(final User user, final String propertyName, final String propertyValue); @Deprecated String getName(); @Deprecated void setName(String name); void setRealmName(String name); String getRealmName(); void setAllowCrossRealmDuplicateNames(boolean allowCrossRealmDuplicateNames); boolean isAllowCrossRealmDuplicateNames(); @Override User getUser(final String name); @Override User getUserById(final String id); @Override User getUser(Subject subject); @Override User getSystemUser(); @Override User getAnonymousUser(); @Override Collection<User> getAllUsers(); void updateUserListWithAllChildren(Node node, Collection<User> users); @Override User createUser(final String name, final String pw); @Override User createUser(final String path, final String name, final String pw); @Override User changePassword(final User user, final String newPassword); @Override void updateLastAccessTimestamp(final User user); @Override Map<String, ACL> getACLs(final User user); @Override User addRole(User user, String roleName); @Override User addGroup(User user, String groupName); @Override User removeGroup(User user, String groupName); @Override User removeRole(User user, String roleName); static final String PROPERTY_EMAIL; static final String PROPERTY_LANGUAGE; static final String PROPERTY_LASTACCESS; static final String PROPERTY_PASSWORD; static final String PROPERTY_TITLE; static final String PROPERTY_ENABLED; static final String NODE_ACLUSERS; }
@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 MgnlUserManager(); Components.setComponentProvider(new MockComponentProvider()); ComponentsTestUtil.setInstance(SystemContext.class, ctx); MgnlContext.setInstance(ctx); when(ctx.getUser()).thenReturn(user); final String workspace = "users"; final Session session = new MockSession(workspace); final Node usersNode = session.getRootNode().addNode(path); when(ctx.getJCRSession(workspace)).thenReturn(session); MgnlContext.setInstance(ctx); um.setProperty(user, propName, new MockValue(propValue)); assertEquals(propValue, usersNode.getProperty(propName).getString()); }
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, String encodedKey); static String encrypt(String pass); static String encrypt(String message, String encodedKey); static String getPrivateKey(); static void updateKeys(MgnlKeyPair keys); static String getPublicKey(); static String byteArrayToHex(byte[] raw); static byte[] hexToByteArray(String s); static MgnlKeyPair generateKeyPair(int keyLength); static String stripPasswordFromCacheLog(String log); static String stripPasswordFromUrl(String url); static String stripParameterFromCacheLog(String log, String parameter); static String getBCrypt(String text); static boolean matchBCrypted(String candidate, String hash); static String getDigest(String data, String algorithm); static byte[] getDigest(byte[] data, String algorithm); static String getSHA1Hex(byte[] data); static String getSHA1Hex(String data); static String getMD5Hex(byte[] data); static String getMD5Hex(String data); static final String SHA1; static final String MD5; static final String SHA256; static final String SHA384; static final String SHA512; }
@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 Properties(); p.load(new FileReader(path)); String publicKey = p.getProperty("key.public"); when(actMan.getPublicKey()).thenReturn(publicKey); doCrypt("bla bla"); doCrypt("1322900338979;johndoe;C750AFBA94E355BF5544434E227708C3"); doCrypt(publicKey); }
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.getPublic().getEncoded())); } static boolean isAnonymous(); static boolean isAuthenticated(); static String decrypt(String pass); static String decrypt(String message, String encodedKey); static String encrypt(String pass); static String encrypt(String message, String encodedKey); static String getPrivateKey(); static void updateKeys(MgnlKeyPair keys); static String getPublicKey(); static String byteArrayToHex(byte[] raw); static byte[] hexToByteArray(String s); static MgnlKeyPair generateKeyPair(int keyLength); static String stripPasswordFromCacheLog(String log); static String stripPasswordFromUrl(String url); static String stripParameterFromCacheLog(String log, String parameter); static String getBCrypt(String text); static boolean matchBCrypted(String candidate, String hash); static String getDigest(String data, String algorithm); static byte[] getDigest(byte[] data, String algorithm); static String getSHA1Hex(byte[] data); static String getSHA1Hex(String data); static String getMD5Hex(byte[] data); static String getMD5Hex(String data); static final String SHA1; static final String MD5; static final String SHA256; static final String SHA384; static final String SHA512; }
@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 boolean isAuthenticated(); static String decrypt(String pass); static String decrypt(String message, String encodedKey); static String encrypt(String pass); static String encrypt(String message, String encodedKey); static String getPrivateKey(); static void updateKeys(MgnlKeyPair keys); static String getPublicKey(); static String byteArrayToHex(byte[] raw); static byte[] hexToByteArray(String s); static MgnlKeyPair generateKeyPair(int keyLength); static String stripPasswordFromCacheLog(String log); static String stripPasswordFromUrl(String url); static String stripParameterFromCacheLog(String log, String parameter); static String getBCrypt(String text); static boolean matchBCrypted(String candidate, String hash); static String getDigest(String data, String algorithm); static byte[] getDigest(byte[] data, String algorithm); static String getSHA1Hex(byte[] data); static String getSHA1Hex(String data); static String getMD5Hex(byte[] data); static String getMD5Hex(String data); static final String SHA1; static final String MD5; static final String SHA256; static final String SHA384; static final String SHA512; }
@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 (18) to render. This might cause timout exceptions on other requests to the same URI. [url=http: } @Test public void testRemoveAllPasswordPamametersFromCacheLog(){ String log = "The following URL took longer than 10 seconds (455812 ms) to render. This might cause timeout exceptions on other requests to the same URI. [url=http: assertEquals(SecurityUtil.stripPasswordFromCacheLog(log), "The following URL took longer than 10 seconds (455812 ms) to render. This might cause timeout exceptions on other requests to the same URI. [url=http: }
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(value, "&"); } static boolean isAnonymous(); static boolean isAuthenticated(); static String decrypt(String pass); static String decrypt(String message, String encodedKey); static String encrypt(String pass); static String encrypt(String message, String encodedKey); static String getPrivateKey(); static void updateKeys(MgnlKeyPair keys); static String getPublicKey(); static String byteArrayToHex(byte[] raw); static byte[] hexToByteArray(String s); static MgnlKeyPair generateKeyPair(int keyLength); static String stripPasswordFromCacheLog(String log); static String stripPasswordFromUrl(String url); static String stripParameterFromCacheLog(String log, String parameter); static String getBCrypt(String text); static boolean matchBCrypted(String candidate, String hash); static String getDigest(String data, String algorithm); static byte[] getDigest(byte[] data, String algorithm); static String getSHA1Hex(byte[] data); static String getSHA1Hex(String data); static String getMD5Hex(byte[] data); static String getMD5Hex(String data); static final String SHA1; static final String MD5; static final String SHA256; static final String SHA384; static final String SHA512; }
@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> delegates); @Override User createUser(final String name, final String pw); @Override User createUser(final String path, final String name, final String pw); @Override User changePassword(User user, String newPassword); @Override User getAnonymousUser(); @Override User getSystemUser(); @Override User getUser(final String name); @Override User getUserById(final String id); @Override User getUser(final Subject subject); @Override Collection<User> getAllUsers(); @Override void updateLastAccessTimestamp(final User user); @Override boolean hasAny(final String principal, final String resourceName, final String resourceTypeName); @Override Map<String,ACL> getACLs(final User user); @Override User addRole(final User user, final String roleName); @Override User addGroup(final User user, final String groupName); @Override int getLockTimePeriod(); @Override int getMaxFailedLoginAttempts(); @Override void setLockTimePeriod(final int lockTimePeriod); @Override void setMaxFailedLoginAttempts(final int maxFailedLoginAttempts); @Override User setProperty(final User user, final String propertyName, final Value propertyValue); @Override User setProperty(final User user, final String propertyName, final String propertyValue); @Override User removeGroup(final User user, final String groupName); @Override User removeRole(final User user, final String roleName); }
@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()); return userManager; } RescueSecuritySupport(); @Override UserManager getUserManager(); @Override UserManager getUserManager(String realmName); @Override GroupManager getGroupManager(); @Override RoleManager getRoleManager(); @Override LoginResult authenticate(CredentialsCallbackHandler callbackHandler, String customLoginModule); }
@Test public void testUserManagerIsAnInstanceOfRescueUserManager() throws Exception { UserManager uman = securitySupport.getUserManager(); assertTrue(uman instanceof RescueUserManager); } @Test public void testUserManagerRealmIsSystemRealm() throws Exception { RescueUserManager uman = (RescueUserManager) securitySupport.getUserManager(); assertEquals(Realm.REALM_SYSTEM.getName(), uman.getRealmName()); } @Test public void testUserManagerReturnsCorrectAnonymousUser() throws Exception { User user = securitySupport.getUserManager().getAnonymousUser(); assertEquals(UserManager.ANONYMOUS_USER, user.getName()); assertEquals("", user.getPassword()); } @Test public void testUserManagerReturnsEnabledRescueUser() throws Exception { User user = securitySupport.getUserManager().getUser(""); assertTrue(user.isEnabled()); } @Test public void testUserManagerReturnsRescueUserWithEnglishAsDefaultLanguage() throws Exception { User user = securitySupport.getUserManager().getUser(""); assertEquals("en", user.getLanguage()); } @Test public void testUserManagerReturnsCorrectSystemUser() throws Exception { User user = securitySupport.getUserManager().getSystemUser(); assertEquals(UserManager.SYSTEM_USER, user.getName()); assertEquals(UserManager.SYSTEM_PSWD, user.getPassword()); } @Test public void testUserManagerReturnsCorrectSystemUserByName() throws Exception { User user = securitySupport.getUserManager().getUser(UserManager.SYSTEM_USER); assertEquals(UserManager.SYSTEM_USER, user.getName()); assertEquals(UserManager.SYSTEM_PSWD, user.getPassword()); } @Test public void testUserManagerReturnsAnonymousUserByAnyNameExcludedSystemUserName() throws Exception { User user = securitySupport.getUserManager().getUser("foo"); assertEquals(UserManager.ANONYMOUS_USER, user.getName()); assertEquals("", user.getPassword()); } @Test public void testUserManagerReturnsSystemUserWithCorrectRole() throws Exception { User user = securitySupport.getUserManager().getSystemUser(); assertTrue(user.hasRole("superuser")); } @Test public void testUserManagerReturnsSystemUserWithCorrectGroup() throws Exception { User user = securitySupport.getUserManager().getSystemUser(); assertTrue(user.inGroup("publishers")); }