method2testcases
stringlengths 118
3.08k
|
---|
### Question:
TemplateDefinitionRegistry { public TemplateDefinition getTemplateDefinition(String id) throws RegistrationException { TemplateDefinitionProvider templateDefinitionProvider; try { templateDefinitionProvider = registry.getRequired(id); } catch (RegistrationException e) { throw new RegistrationException("No template definition registered for id: " + id, e); } return templateDefinitionProvider.getTemplateDefinition(); } TemplateDefinition getTemplateDefinition(String id); Collection<TemplateDefinition> getTemplateDefinitions(); void register(TemplateDefinitionProvider provider); void unregister(String id); Set<String> unregisterAndRegister(Collection<String> registeredIds, Collection<TemplateDefinitionProvider> providers); }### Answer:
@Test(expected = RegistrationException.class) public void testGetTemplateDefinitionThrowsOnBadId() throws RegistrationException { TemplateDefinitionRegistry registry = new TemplateDefinitionRegistry(); registry.getTemplateDefinition("nonExistingId"); } |
### Question:
TemplateDefinitionRegistry { public Set<String> unregisterAndRegister(Collection<String> registeredIds, Collection<TemplateDefinitionProvider> providers) { return registry.removeAndPutAll(registeredIds, providers); } TemplateDefinition getTemplateDefinition(String id); Collection<TemplateDefinition> getTemplateDefinitions(); void register(TemplateDefinitionProvider provider); void unregister(String id); Set<String> unregisterAndRegister(Collection<String> registeredIds, Collection<TemplateDefinitionProvider> providers); }### Answer:
@Test public void testUnregisterAndRegister() { String providerId = "onlyOneToRemove"; final TemplateDefinitionRegistry registry = new TemplateDefinitionRegistry(); TemplateDefinitionProvider provider = mock(TemplateDefinitionProvider.class); when(provider.getId()).thenReturn(providerId); registry.register(provider); List<String> idsToRemove = new ArrayList<String>(); idsToRemove.add(providerId); TemplateDefinitionProvider rp1 = mock(TemplateDefinitionProvider.class); when(rp1.getId()).thenReturn("rp1"); TemplateDefinitionProvider rp2 = mock(TemplateDefinitionProvider.class); when(rp2.getId()).thenReturn("rp2"); registry.register(rp1); registry.register(rp2); List<TemplateDefinitionProvider> rendererProviders = new ArrayList<TemplateDefinitionProvider>(); rendererProviders.add(provider); Set<String> idsOfNewRegisteredProviders = registry.unregisterAndRegister(idsToRemove, rendererProviders); assertTrue(idsOfNewRegisteredProviders.contains(providerId)); assertEquals(1, idsOfNewRegisteredProviders.size()); } |
### Question:
ConfiguredAreaDefinition extends ConfiguredTemplateDefinition implements AreaDefinition { @Override public Map<String, ComponentAvailability> getAvailableComponents() { return availableComponents; } @Override Map<String, ComponentAvailability> getAvailableComponents(); void setAvailableComponents(Map<String, ComponentAvailability> availableComponents); void addAvailableComponent(String name, ComponentAvailability configuredComponentAvailability); @Override Boolean isEnabled(); void setEnabled(Boolean enabled); @Override String getType(); void setType(String type); @Override String getContentStructure(); void setContentStructure(String contentStructure); @Override InheritanceConfiguration getInheritance(); void setInheritance(InheritanceConfiguration inheritanceConfiguration); @Override Boolean isOptional(); void setOptional(Boolean optional); @Override Integer getMaxComponents(); void setMaxComponents(Integer maxComponents); }### Answer:
@Test public void testAvailableComponentsIsInitiallyEmpty() { ConfiguredAreaDefinition def = new ConfiguredAreaDefinition(); int componentsSize = def.getAvailableComponents().size(); assertEquals(0, componentsSize); } |
### Question:
ConfiguredAreaDefinition extends ConfiguredTemplateDefinition implements AreaDefinition { public void setAvailableComponents(Map<String, ComponentAvailability> availableComponents) { this.availableComponents = availableComponents; } @Override Map<String, ComponentAvailability> getAvailableComponents(); void setAvailableComponents(Map<String, ComponentAvailability> availableComponents); void addAvailableComponent(String name, ComponentAvailability configuredComponentAvailability); @Override Boolean isEnabled(); void setEnabled(Boolean enabled); @Override String getType(); void setType(String type); @Override String getContentStructure(); void setContentStructure(String contentStructure); @Override InheritanceConfiguration getInheritance(); void setInheritance(InheritanceConfiguration inheritanceConfiguration); @Override Boolean isOptional(); void setOptional(Boolean optional); @Override Integer getMaxComponents(); void setMaxComponents(Integer maxComponents); }### Answer:
@Test public void testSetAvailableComponents() { ConfiguredAreaDefinition def = new ConfiguredAreaDefinition(); Map<String, ComponentAvailability> newMap = Collections.<String, ComponentAvailability> emptyMap(); def.setAvailableComponents(newMap); assertEquals(newMap, def.getAvailableComponents()); } |
### Question:
MetaDataBasedTemplateDefinitionAssignment implements TemplateDefinitionAssignment { @Override public TemplateDefinition getAssignedTemplateDefinition(Node content) throws RegistrationException { final String templateId; try { templateId = getAssignedTemplate(content); } catch (RepositoryException e) { throw new RegistrationException("Could not determine assigned template", e); } if (templateId == null) { throw new RegistrationException("No template definition assigned"); } return templateDefinitionRegistry.getTemplateDefinition(templateId); } @Inject MetaDataBasedTemplateDefinitionAssignment(TemplateDefinitionRegistry templateDefinitionRegistry); @Override String getAssignedTemplate(Node content); @Override TemplateDefinition getAssignedTemplateDefinition(Node content); @Override TemplateDefinition getDefaultTemplate(Node content); @Override Collection<TemplateDefinition> getAvailableTemplates(Node content); }### Answer:
@Test public void testGetAssignedTemplateDefinition() throws Exception { final String templateId = "id"; MockNode node = new MockNode(); node.addMixin(NodeTypes.Renderable.NAME); NodeTypes.Renderable.set(node, templateId); TemplateDefinitionRegistry registry = new TemplateDefinitionRegistry(); TemplateDefinition templateDefinition = mock(TemplateDefinition.class); TemplateDefinitionProvider provider = mock(TemplateDefinitionProvider.class); when(provider.getId()).thenReturn(templateId); when(provider.getTemplateDefinition()).thenReturn(templateDefinition); registry.register(provider); MetaDataBasedTemplateDefinitionAssignment assignment = new MetaDataBasedTemplateDefinitionAssignment(registry); TemplateDefinition result = assignment.getAssignedTemplateDefinition(node); assertEquals(templateDefinition, result); } |
### Question:
ChannelVariationResolver implements RenderableVariationResolver { @Override public RenderableDefinition resolveVariation(RenderableDefinition renderableDefinition) { if(!MgnlContext.isWebContext()){ return null; } final AggregationState aggregationState = MgnlContext.getAggregationState(); final String channelName = aggregationState.getChannel().getName(); RenderableDefinition defVariation = renderableDefinition.getVariations().get(channelName); if (defVariation == null) { return null; } return BeanMergerUtil.merge(defVariation, renderableDefinition); } @Override RenderableDefinition resolveVariation(RenderableDefinition renderableDefinition); }### Answer:
@Test public void testChoosesTemplateVariationIfProperlySet() throws Exception { final MockWebContext mockContext = (MockWebContext) MockUtil.initMockContext(); final Channel channel = new Channel(); channel.setName(TEST_TEMPLATE_VARIATION_NAME); mockContext.getAggregationState().setChannel(channel); final ChannelVariationResolver resolver = new ChannelVariationResolver(); RenderableDefinition result = resolver.resolveVariation(templateDefinition); assertEquals(TEST_TEMPLATE_VARIATION_NAME, result.getName()); assertEquals("this-is-an-overriding-templateScript", result.getTemplateScript()); assertEquals("this-will-be-reused-by-the-variation", result.getDescription()); }
@Test public void testDoesNothingWhenVariationDoesntExist() throws Exception { MockWebContext mockContext = (MockWebContext) MockUtil.initMockContext(); final Channel channel = new Channel(); channel.setName("doesNotExist"); mockContext.getAggregationState().setChannel(channel); final ChannelVariationResolver resolver = new ChannelVariationResolver(); RenderableDefinition result = resolver.resolveVariation(templateDefinition); assertNull(result); }
@Test public void testDoesNothingWhenAggregationStateNotAvailable() throws Exception { final ChannelVariationResolver resolver = new ChannelVariationResolver(); final RenderableDefinition result = resolver.resolveVariation(templateDefinition); assertNull(result); } |
### Question:
ExtensionVariationResolver implements RenderableVariationResolver { @Override public RenderableDefinition resolveVariation(RenderableDefinition renderableDefinition) { AggregationState aggregationState = getAggregationStateSafely(); if (aggregationState == null) { return null; } String extension = aggregationState.getExtension(); RenderableDefinition variation = renderableDefinition.getVariations().get(extension); if (variation == null) { return null; } return BeanMergerUtil.merge(variation, renderableDefinition); } @Override RenderableDefinition resolveVariation(RenderableDefinition renderableDefinition); }### Answer:
@Test public void testChoosesVariantWhenExtensionMatch() throws Exception { MockWebContext mockContext = (MockWebContext) MockUtil.initMockContext(); mockContext.getAggregationState().setExtension("xml"); ExtensionVariationResolver resolver = new ExtensionVariationResolver(); RenderableDefinition result = resolver.resolveVariation(templateDefinition); assertEquals("this-is-an-overriding-templateScript", result.getTemplateScript()); assertEquals("this-will-be-reused-by-the-variation", result.getDescription()); }
@Test public void testChoosesTemplateWhenExtensionDoesntMatch() throws Exception { MockWebContext mockContext = (MockWebContext) MockUtil.initMockContext(); mockContext.getAggregationState().setExtension("pdf"); ExtensionVariationResolver resolver = new ExtensionVariationResolver(); RenderableDefinition result = resolver.resolveVariation(templateDefinition); assertNull(result); }
@Test public void testDoesNothingWhenAggregationStateNotAvailable() throws Exception { ExtensionVariationResolver resolver = new ExtensionVariationResolver(); RenderableDefinition result = resolver.resolveVariation(templateDefinition); assertNull(result); } |
### Question:
JCRAuthenticationModule extends AbstractLoginModule implements UserAwareLoginModule, Serializable { @Override public void validateUser() throws LoginException { initUser(); if (this.user == null) { throw new AccountNotFoundException("User account " + this.name + " not found."); } if (!this.user.isEnabled()) { throw new AccountLockedException("User account " + this.name + " is locked."); } matchPassword(); if (!UserManager.ANONYMOUS_USER.equals(user.getName())) { getUserManager().updateLastAccessTimestamp(user); } } int getMaxAttempts(); long getTimeLock(); @Override void validateUser(); @Override void setEntity(); @Override void setACL(); void collectRoleNames(); void collectGroupNames(); @Override User getUser(); }### Answer:
@Test public void testValidateUserPassesIfPasswordsMatch() throws Exception { JCRAuthenticationModule authenticationModule = new JCRAuthenticationModule(); authenticationModule.name = FOO_USERNAME; authenticationModule.pswd = PLAIN_TXT_FOO_PSWD.toCharArray(); authenticationModule.validateUser(); authenticationModule.name = UserManager.SYSTEM_USER; authenticationModule.pswd = UserManager.SYSTEM_PSWD.toCharArray(); authenticationModule.validateUser(); }
@Test(expected=FailedLoginException.class) public void testValidateUserFailsIfPasswordsDoNotMatch() throws Exception { JCRAuthenticationModule authenticationModule = new JCRAuthenticationModule(); authenticationModule.name = FOO_USERNAME; authenticationModule.pswd = "hghgh".toCharArray(); authenticationModule.validateUser(); authenticationModule.name = UserManager.SYSTEM_USER; authenticationModule.pswd = "blah".toCharArray(); authenticationModule.validateUser(); } |
### Question:
SearchResultSnippetTag extends TagSupport { protected String stripHtmlTags(String input) { return HTML_STRIP.matcher(input).replaceAll(""); } void setQuery(String query); void setChars(int chars); void setMaxSnippets(int maxSnippets); void setPage(Node page); @Override int doStartTag(); Collection getSnippets(); @Override void release(); }### Answer:
@Test public void testStripHtmlSimple() { String html = "<div>uh!</div>"; String text = "uh!"; String result = new SearchResultSnippetTag().stripHtmlTags(html); assertEquals(text, result); }
@Test public void testStripHtmlEmptyTag() { String html = "<div>uh!<br/></div>"; String text = "uh!"; String result = new SearchResultSnippetTag().stripHtmlTags(html); assertEquals(text, result); }
@Test public void testStripHtmlNewLines() { String html = "<div\n class=\"abc\">uh!</div>"; String text = "uh!"; String result = new SearchResultSnippetTag().stripHtmlTags(html); assertEquals(text, result); }
@Test public void testStripHtmlMultipleNewLines() { String html = "<div\n class=\"abc\"\n style=\"abc\">uh!</div>"; String text = "uh!"; String result = new SearchResultSnippetTag().stripHtmlTags(html); assertEquals(text, result); }
@Test public void testStripHtmlNewLineAsLast() { String html = "<div\n class=\"abc\"\n style=\"abc\"\n>uh!</div>"; String text = "uh!"; String result = new SearchResultSnippetTag().stripHtmlTags(html); assertEquals(text, result); } |
### Question:
PoweredByTag extends SimpleTagSupport { @Override public void doTag() throws JspException, IOException { final Writer out = getJspContext().getOut(); final LicenseFileExtractor license = LicenseFileExtractor.getInstance(); final String[] licenseValues = new String[] { license.get(LicenseFileExtractor.EDITION), license.get(LicenseFileExtractor.VERSION_NUMBER), license.get(LicenseFileExtractor.BUILD_NUMBER), license.get(LicenseFileExtractor.PRODUCT_DOMAIN), license.get(LicenseFileExtractor.PROVIDER), license.get(LicenseFileExtractor.PROVIDER_ADDRESS), license.get(LicenseFileExtractor.PROVIDER_EMAIL), }; final String message = MessageFormat.format(pattern, licenseValues); out.write(message); } void setPattern(String pattern); @Override void doTag(); }### Answer:
@Test public void testShouldBeUseableWithoutAnyAttribute() throws Exception { final PoweredByTag tag = new PoweredByTag(); tag.setJspContext(pageContext); tag.doTag(); assertJspContent("Powered by <a href=\"http: } |
### Question:
BeanMergerUtil { public static <T> T merge(Object... sources) { final ArrayList list = new ArrayList(); CollectionUtils.addAll(list, sources); return (T) merger.merge(list); } static T merge(Object... sources); }### Answer:
@Test public void testBeanMergerUtilProperlyHandsOverProvidedObjects() { final Object first2Merge = "a"; final Object second2Merge = "b"; List<Object> result = BeanMergerUtil.merge(first2Merge, second2Merge); assertEquals(result.get(0), first2Merge); assertEquals(result.get(1), second2Merge); } |
### Question:
EditorLinkTransformer implements LinkTransformer { @Override public String transform(Link uuidLink) { return new AbsolutePathTransformer(true,true,false).transform(uuidLink); } @Override String transform(Link uuidLink); }### Answer:
@Test public void testEditorLinkTransformation(){ link.setHandle("/path"); link.setNodeDataName("nodeData"); link.setFileName("fileName"); link.setExtension("ext"); when(ctx.getContextPath()).thenReturn("context"); String result = editorTransformer.transform(link); assertEquals("context/path/nodeData/fileName.ext", result); } |
### Question:
ComponentConfigurationReader { public ComponentsDefinition readFromResource(String resourcePath) { final InputStreamReader reader = new InputStreamReader(getClass().getResourceAsStream(resourcePath)); try { return read(reader); } finally { try { reader.close(); } catch (IOException e) { log.error("Can't close input for " + resourcePath); } } } ComponentConfigurationReader(); List<ComponentsDefinition> readAll(List<String> resourcePaths); ComponentsDefinition read(Reader in); ComponentsDefinition readFromResource(String resourcePath); }### Answer:
@Test public void testCanReadPlatformComponentsFile() { ComponentConfigurationReader reader = new ComponentConfigurationReader(); ComponentsDefinition componentsDefinition = reader.readFromResource(MagnoliaServletContextListener.DEFAULT_PLATFORM_COMPONENTS_CONFIG_LOCATION); assertTrue(componentsDefinition.getComponents().size() > 0); } |
### Question:
ObservedComponentFactory implements ComponentFactory<T>, EventListener { @Override @SuppressWarnings("unchecked") public T newInstance() { if (getObservedObject() == null) { log.warn("An instance of {} couldn't be loaded from {}:{} yet, returning null.", new Object[]{interf, repository, path}); return null; } return (T) new CglibProxyFactory().createDelegatorProxy(new ObjectProvider() { @Override public Object getObject() { return getObservedObject(); } }, new Class[]{ getObservedObject().getClass() }); } ObservedComponentFactory(String repository, String path, Class<T> type); ObservedComponentFactory(String repository, String path, Class<T> type, ComponentProvider componentProvider); @Override @SuppressWarnings("unchecked") // until commons-proxy becomes generics-aware, we have to ignore this warning T newInstance(); @Override void onEvent(EventIterator events); @Deprecated T getObservedObject(); @Override String toString(); }### Answer:
@Test public void testReturnsAProxyToGivenTypeIfConcreteClassEvenIfPathDoesNotExistYet() throws Exception { MockUtil.createAndSetHierarchyManager("test", "/foo"); final ObservedComponentFactory<MyComponent> compFac = new NonObservingObservedComponentFactory("test", "/foo/bar", MyComponent.class); final MyComponent observedCompo = compFac.newInstance(); assertNotNull(observedCompo); assertEquals("default", observedCompo.getTheString()); } |
### Question:
DefaultMagnoliaInitPaths implements MagnoliaInitPaths { @Override public String getRootPath() { return rootPath; } @Inject DefaultMagnoliaInitPaths(MagnoliaServletContextListener magnoliaServletContextListener, final ServletContext servletContext); @Override String getServerName(); @Override String getRootPath(); @Override String getWebappFolderName(); @Override String getContextPath(); }### Answer:
@Test public void testDetermineRootPathJustWorks() { MagnoliaInitPaths paths = expectServletContextRealPath("/foo/bar"); assertEquals("/foo/bar", paths.getRootPath()); }
@Test public void testDetermineRootPathStripsTrailingSlash() { MagnoliaInitPaths paths = expectServletContextRealPath("/foo/bar/"); assertEquals("/foo/bar", paths.getRootPath()); }
@Test public void testDetermineRootPathTranslatesBackslashes() { MagnoliaInitPaths paths = expectServletContextRealPath("\\foo\\bar"); assertEquals("/foo/bar", paths.getRootPath()); }
@Test public void testDetermineRootPathTranslatesBackslashesAndStripsTrailingSlash() { MagnoliaInitPaths paths = expectServletContextRealPath("\\foo\\bar\\"); assertEquals("/foo/bar", paths.getRootPath()); } |
### Question:
DefaultMagnoliaInitPaths implements MagnoliaInitPaths { @Override public String getWebappFolderName() { return webappFolderName; } @Inject DefaultMagnoliaInitPaths(MagnoliaServletContextListener magnoliaServletContextListener, final ServletContext servletContext); @Override String getServerName(); @Override String getRootPath(); @Override String getWebappFolderName(); @Override String getContextPath(); }### Answer:
@Test public void testDetermineWebappFolderNameJustWorks() { MagnoliaInitPaths paths = expectServletContextRealPath("/foo/bar"); assertEquals("bar", paths.getWebappFolderName()); }
@Test public void testDetermineWebappFolderNameWorksWithTrailingSlashes() { MagnoliaInitPaths paths = expectServletContextRealPath("/foo/bar/"); assertEquals("bar", paths.getWebappFolderName()); }
@Test public void testDetermineWebappFolderNameWorksWithBackslashes() { MagnoliaInitPaths paths = expectServletContextRealPath("\\foo\\bar"); assertEquals("bar", paths.getWebappFolderName()); }
@Test public void testDetermineWebappFolderNameWorksWithTrailingSlashesAndBackslashes() { MagnoliaInitPaths paths = expectServletContextRealPath("\\foo\\bar\\"); assertEquals("bar", paths.getWebappFolderName()); } |
### Question:
AbstractMagnoliaConfigurationProperties implements MagnoliaConfigurationProperties { @Override public String getProperty(String key) { final PropertySource propertySource = getPropertySource(key); if (propertySource != null) { final String value = propertySource.getProperty(key); return parseStringValue(value, new HashSet<String>()); } return null; } protected AbstractMagnoliaConfigurationProperties(List<PropertySource> propertySources); @Override void init(); @Override Set<String> getKeys(); @Override PropertySource getPropertySource(String key); @Override String getProperty(String key); @Override boolean getBooleanProperty(String property); @Override boolean hasProperty(String key); @Override String describe(); @Override String toString(); }### Answer:
@Test public void testSimpleProperty() throws Exception { assertEquals("property", p.getProperty("test.one")); }
@Test public void testNestedProperty() throws Exception { assertEquals("nested property", p.getProperty("test.two")); }
@Test public void testNestedPropertyMoreLevels() throws Exception { assertEquals("another nested property", p.getProperty("test.three")); }
@Test public void testNestedSomeMore() throws Exception { assertEquals("nest property nested property another nested property", p.getProperty("test.four")); }
@Test public void testCircularProperty() throws Exception { assertEquals("${test.circular2}", p.getProperty("test.circular1")); assertEquals("${test.circular1}", p.getProperty("test.circular2")); }
@Test public void testSelfReferencingProperty() throws Exception { assertEquals("${test.circular3}", p.getProperty("test.circular3")); }
@Test public void testValuesAreTrimmed() throws Exception { assertEquals("foo", p.getProperty("test.whitespaces")); }
@Test public void testValuesForNestedPropertiesAreTrimmed() throws Exception { assertEquals("bar foo", p.getProperty("test.whitespaces.nested")); } |
### Question:
MagnoliaServletContextListener implements ServletContextListener { @Override public void contextInitialized(final ServletContextEvent sce) { contextInitialized(sce, true); } @Override void contextInitialized(final ServletContextEvent sce); void contextInitialized(final ServletContextEvent sce, boolean startServer); @Override void contextDestroyed(final ServletContextEvent sce); static final String PLATFORM_COMPONENTS_CONFIG_LOCATION_NAME; static final String DEFAULT_PLATFORM_COMPONENTS_CONFIG_LOCATION; }### Answer:
@Test public void testNullSeverNameIsSetToDeault() throws Exception { testInitPath = new TestMagnoliaInitPaths(null, "/tmp/magnoliaTests", "magnoliaTests", "/test"); initProperties = new TestMagnoliaConfigurationProperties(); ctxListener = new MagnoliaServletContextListener() { protected ComponentProviderConfiguration getPlatformComponents() { return configurationSetUp(); }; }; ctxListener.contextInitialized(sce); assertEquals("default", System.getProperty("server")); } |
### Question:
VersionUtil { public static String getNodeTypeName(Node node) throws RepositoryException { node = NodeUtil.deepUnwrap(node, JCRPropertiesFilteringNodeWrapper.class); if (node.hasProperty(JcrConstants.JCR_FROZENPRIMARYTYPE)) { return node.getProperty(JcrConstants.JCR_FROZENPRIMARYTYPE).getString(); } return node.getProperty(JcrConstants.JCR_PRIMARYTYPE).getString(); } static String getNodeTypeName(Node node); }### Answer:
@Test public void testGetNodeTypeName() throws Exception { String primaryTypeName = "primaryTypeValue"; final MockNode node = new MockNode("test", primaryTypeName); assertEquals(primaryTypeName, VersionUtil.getNodeTypeName(node)); final String frozenPrimaryTypeName = "frozenPrimaryTypeValue"; node.setProperty(JcrConstants.JCR_FROZENPRIMARYTYPE, frozenPrimaryTypeName); assertEquals(frozenPrimaryTypeName, VersionUtil.getNodeTypeName(node)); final Node wrapper = new JCRPropertiesFilteringNodeWrapper(node); assertEquals(frozenPrimaryTypeName, VersionUtil.getNodeTypeName(wrapper)); } |
### Question:
PropertyUtil { public static boolean getBoolean(Node node, String name, boolean defaultValue) { try { if (node.hasProperty(name)) { return node.getProperty(name).getBoolean(); } } catch (RepositoryException e) { log.error("can't read value '" + name + "' of the Node '" + node.toString() + "' will return default value", e); } return defaultValue; } static void renameProperty(Property property, String newName); @SuppressWarnings("unchecked") static void setProperty(Node node, String propertyName, Object propertyValue); static Value createValue(String valueStr, int type, ValueFactory valueFactory); static int getJCRPropertyType(Object obj); static void updateOrCreate(Node node, String string, GregorianCalendar gregorianCalendar); static String getDateFormat(); static List<String> getValuesStringList(Value[] values); static String getValueString(Property property); static String getValueString(Value value); static Value createValue(Object obj, ValueFactory valueFactory); static Calendar getDate(Node node, String name); static Calendar getDate(Node node, String name, Calendar defaultValue); static String getString(Node node, String name); static String getString(Node node, String name, String defaultValue); static boolean getBoolean(Node node, String name, boolean defaultValue); static Property getPropertyOrNull(Node node, String relativePath); static Property getProperty(Node node, String relativePath); static Object getPropertyValueObject(Node node, String relativePath); static Object getValueObject(Value value); }### Answer:
@Test public void testGetBoolean() throws RepositoryException { boolean defaultValue = false; boolean value = true; root.setProperty(PROPERTY_NAME, value); boolean res = PropertyUtil.getBoolean(root, PROPERTY_NAME, defaultValue); assertEquals(value, res); } |
### Question:
PropertyUtil { public static Property getPropertyOrNull(Node node, String relativePath) { try { return node.hasProperty(relativePath) ? node.getProperty(relativePath) : null; } catch (RepositoryException e) { log.debug("Could not retrieve property " + relativePath, e); } return null; } static void renameProperty(Property property, String newName); @SuppressWarnings("unchecked") static void setProperty(Node node, String propertyName, Object propertyValue); static Value createValue(String valueStr, int type, ValueFactory valueFactory); static int getJCRPropertyType(Object obj); static void updateOrCreate(Node node, String string, GregorianCalendar gregorianCalendar); static String getDateFormat(); static List<String> getValuesStringList(Value[] values); static String getValueString(Property property); static String getValueString(Value value); static Value createValue(Object obj, ValueFactory valueFactory); static Calendar getDate(Node node, String name); static Calendar getDate(Node node, String name, Calendar defaultValue); static String getString(Node node, String name); static String getString(Node node, String name, String defaultValue); static boolean getBoolean(Node node, String name, boolean defaultValue); static Property getPropertyOrNull(Node node, String relativePath); static Property getProperty(Node node, String relativePath); static Object getPropertyValueObject(Node node, String relativePath); static Object getValueObject(Value value); }### Answer:
@Test public void testGetPropertyOrNull() throws RepositoryException { final String propertyValue = "value"; final String propertyName = "myProperty"; root.setProperty(propertyName, propertyValue); final Property res = PropertyUtil.getPropertyOrNull(root, "myProperty"); assertEquals("Props Name should be " + propertyName, propertyName, res.getName()); assertEquals("Props Value should be " + propertyValue, propertyValue, res.getString()); } |
### Question:
SessionUtil { public static boolean hasSameUnderlyingSession(Session first, Session second) { return unwrap(first).equals(unwrap(second)); } static boolean hasSameUnderlyingSession(Session first, Session second); static Session unwrap(Session session); static Node getNode(String repository, String path); static Node getNodeByIdentifier(String repository, String id); }### Answer:
@Test public void testHasSameUnderlyingSessionWithTwoWrappersOnSameSession() { final Session session = mock(Session.class); final Session wrapperOne = new MgnlVersioningSession(session); final Session wrapperTwo = new MgnlVersioningSession(session); boolean result = SessionUtil.hasSameUnderlyingSession(wrapperOne, wrapperTwo); assertTrue(result); }
@Test public void testHasSameUnderlyingSessionWithOneWrapperOnDifferentSession() { final Session jcrSession = mock(Session.class); final Session otherSession = mock(Session.class); final Session wrapperOne = new MgnlVersioningSession(jcrSession); boolean result = SessionUtil.hasSameUnderlyingSession(otherSession, wrapperOne); assertFalse(result); }
@Test public void testHasSameUnderlyingSessionWithTwoUnwrappedSessions() { final Session jcrSession = mock(Session.class); final Session otherSession = mock(Session.class); boolean result = SessionUtil.hasSameUnderlyingSession(jcrSession, otherSession); assertFalse(result); } |
### Question:
SessionUtil { public static Node getNode(String repository, String path) { Node res = null; Session session; if (StringUtils.isBlank(repository) || StringUtils.isBlank(path)) { log.debug("getNode returns null because either nodePath: '" + path + "' or repository: '" + repository + "' is empty"); return res; } try { session = MgnlContext.getJCRSession(repository); if (session != null) { res = session.getNode(path); } } catch (RepositoryException e) { log.error("Exception during node Search for nodePath: '" + path + "' in repository: '" + repository + "'", e); } return res; } static boolean hasSameUnderlyingSession(Session first, Session second); static Session unwrap(Session session); static Node getNode(String repository, String path); static Node getNodeByIdentifier(String repository, String id); }### Answer:
@Test public void testGetNode() throws RepositoryException { Node addedNode = MgnlContext.getJCRSession(WEBSITE).getRootNode().addNode("1"); Node returnedNode = SessionUtil.getNode(WEBSITE, addedNode.getPath()); assertEquals(addedNode, returnedNode); }
@Test public void testGetNodeNoSessionPassed() throws RepositoryException { Node addedNode = MgnlContext.getJCRSession(WEBSITE).getRootNode().addNode("1"); Node returnedNode = SessionUtil.getNode(null, addedNode.getPath()); assertEquals(null, returnedNode); }
@Test public void testGetNodeBadPath() throws RepositoryException { Node addedNode = MgnlContext.getJCRSession(WEBSITE).getRootNode().addNode("1"); Node returnedNode = SessionUtil.getNode(WEBSITE, addedNode.getPath() + 1); assertEquals(null, returnedNode); } |
### Question:
SessionUtil { public static Node getNodeByIdentifier(String repository, String id) { Node res = null; Session session; if (StringUtils.isBlank(repository) || StringUtils.isBlank(id)) { log.debug("getNode returns null because either identifier: '" + id + "' or repository: '" + repository + "' is empty"); return res; } try { session = MgnlContext.getJCRSession(repository); if (session != null) { res = session.getNodeByIdentifier(id); } } catch (RepositoryException e) { log.error("Exception during node Search by identifier: '" + id + "' in repository: '" + repository + "'", e); } return res; } static boolean hasSameUnderlyingSession(Session first, Session second); static Session unwrap(Session session); static Node getNode(String repository, String path); static Node getNodeByIdentifier(String repository, String id); }### Answer:
@Test public void testGetNodeByIdentifier() throws RepositoryException { Node addedNode = MgnlContext.getJCRSession(WEBSITE).getRootNode().addNode("1"); Node returnedNode = SessionUtil.getNodeByIdentifier(WEBSITE, addedNode.getIdentifier()); assertEquals(addedNode, returnedNode); }
@Test public void testGetNodeByIdentifierNoSessionPassed() throws RepositoryException { Node addedNode = MgnlContext.getJCRSession(WEBSITE).getRootNode().addNode("1"); Node returnedNode = SessionUtil.getNodeByIdentifier(null, addedNode.getIdentifier()); assertEquals(null, returnedNode); }
@Test public void testGetNodeByIdentifierBadId() throws RepositoryException { Node addedNode = MgnlContext.getJCRSession(WEBSITE).getRootNode().addNode("1"); Node returnedNode = SessionUtil.getNodeByIdentifier(WEBSITE, addedNode.getIdentifier() + 1); assertEquals(null, returnedNode); } |
### Question:
MetaDataUtil { public static MetaData getMetaData(Node node) { return new MetaData(node); } static MetaData getMetaData(Node node); static void updateMetaData(Node node); static Calendar getLastModification(Node node); static String getTemplate(Node node); }### Answer:
@Test public void testGetMetaData() throws Exception { MetaData md = MetaDataUtil.getMetaData(testNode); assertNotNull(md); } |
### Question:
MetaDataUtil { public static void updateMetaData(Node node) throws RepositoryException { MetaData md = getMetaData(node); md.setModificationDate(); md.setAuthorId(MgnlContext.getUser().getName()); AuditLoggingUtil.log(AuditLoggingUtil.ACTION_MODIFY, node.getSession().getWorkspace().getName(), node .getPrimaryNodeType().getName(), node.getName()); } static MetaData getMetaData(Node node); static void updateMetaData(Node node); static Calendar getLastModification(Node node); static String getTemplate(Node node); }### Answer:
@Test public void testUpdateMetaData() throws Exception { final String testUserName = "test"; final Context ctx = mock(Context.class); final User user = mock(User.class); MgnlContext.setInstance(ctx); when(ctx.getUser()).thenReturn(user); when(user.getName()).thenReturn(testUserName); MetaData metaData = MetaDataUtil.getMetaData(testNode); MetaDataUtil.updateMetaData(testNode); Date lastMod = metaData.getModificationDate().getTime(); long diff = System.currentTimeMillis() - lastMod.getTime(); assertTrue("lastMod hast not been updated in the last 500ms - it was only " + diff + "ms!" , diff < 500); assertEquals(testUserName, metaData.getAuthorId()); } |
### Question:
ContentDecoratorUtil { public static boolean isDecoratedWith(Node node, Class<? extends ContentDecorator> clazz) { while (node instanceof DelegateNodeWrapper) { if (node instanceof ContentDecoratorNodeWrapper) { ContentDecorator contentDecorator = ((ContentDecoratorNodeWrapper) node).getContentDecorator(); if (clazz.isInstance(contentDecorator)) { return true; } } node = ((DelegateNodeWrapper) node).getWrappedNode(); } return false; } static boolean isDecoratedWith(Node node, Class<? extends ContentDecorator> clazz); }### Answer:
@Test public void returnsFalseWhenNotDecorated() { Node node = new MockNode(); assertFalse(ContentDecoratorUtil.isDecoratedWith(node, ContentDecoratorSuperClass.class)); }
@Test public void returnsTrueWhenQueriedForExactClass() { Node node = new MockNode(); node = new ContentDecoratorSuperClass().wrapNode(node); assertTrue(ContentDecoratorUtil.isDecoratedWith(node, ContentDecoratorSuperClass.class)); }
@Test public void returnsTrueWhenQueriedForSubClass() { Node node = new MockNode(); node = new ContentDecoratorSubClass().wrapNode(node); assertTrue(ContentDecoratorUtil.isDecoratedWith(node, ContentDecoratorSuperClass.class)); }
@Test public void returnsFalseWhenDecoratedByOtherDecorator() { Node node = new MockNode(); node = new ContentDecoratorSuperClass().wrapNode(node); assertFalse(ContentDecoratorUtil.isDecoratedWith(node, ContentDecoratorSubClass.class)); } |
### Question:
AbstractNodeOperation implements NodeOperation { @Override public NodeOperation then(NodeOperation... childrenOps) { CollectionUtils.addAll(this.childrenOps, childrenOps); return this; } @Override void exec(Node context, ErrorHandler errorHandler); @Override NodeOperation then(NodeOperation... childrenOps); }### Answer:
@Test public void testThen() throws RepositoryException { final String rootNodeName = "root"; final String subName = "firstSub"; final String subSubName = "secondSub"; final MockNode rootNode = new MockNode(rootNodeName); final NodeOperation addNodeOp = Ops.addNode(subName); final NodeOperation addAnotherNode = Ops.addNode(subSubName); addNodeOp.then(addAnotherNode); addNodeOp.exec(rootNode, new RuntimeExceptionThrowingErrorHandler()); assertTrue(rootNode.hasNode(subName)); assertTrue(rootNode.getNode(subName).hasNode(subSubName)); } |
### Question:
NodeBuilder { public void exec() throws NodeOperationException { for (NodeOperation childrenOp : childrenOps) { childrenOp.exec(root, errorHandler); } } NodeBuilder(Node root, NodeOperation... childrenOps); NodeBuilder(ErrorHandler errorHandler, Node root, NodeOperation... childrenOps); void exec(); }### Answer:
@Test public void testExecWithSeveralChildOps() throws Exception { final NodeOperation addNodeOp = Ops.addNode(CHILD_NAME); final NodeOperation addPropertyOp = Ops.addProperty(PROPERTY_NAME, PROPERTY_VALUE); final Node rootNode = session.getRootNode(); NodeBuilder builder = new NodeBuilder(rootNode, addNodeOp, addPropertyOp); builder.exec(); assertTrue("AddNode Operation failed!", rootNode.hasNode(CHILD_NAME)); assertEquals("AddProperty Operation failed!", propertyValue, rootNode.getProperty(PROPERTY_NAME).getValue()); }
@Test public void testRealisticUsageScenario() throws RepositoryException { final Node rootNode = session.getRootNode(); final MockNode childNode = (MockNode) rootNode.addNode(CHILD_NAME); final String childOfChildName = "childOfChild"; NodeBuilder builder = new NodeBuilder(rootNode, getNode(CHILD_NAME).then( addNode(childOfChildName).then(addProperty(PROPERTY_NAME, PROPERTY_VALUE)))); builder.exec(); assertTrue(childNode.hasNode(childOfChildName)); assertEquals("AddProperty Operation failed!", propertyValue, childNode.getNode(childOfChildName).getProperty(PROPERTY_NAME).getValue()); } |
### Question:
Ops { public static NodeOperation addNode(final String name) { return new AbstractNodeOperation() { @Override protected Node doExec(Node context, ErrorHandler errorHandler) throws RepositoryException { return context.addNode(name); } }; } static NodeOperation addNode(final String name); static NodeOperation addNode(final String name, final String type); static NodeOperation getNode(final String name); static NodeOperation addProperty(final String name, final String newValue); static NodeOperation setProperty(final String name, final Object newValue); static NodeOperation renameNode(final String currentName, final String newName); static NodeOperation renameProperty(final String name, final String newName); static NodeOperation moveNode(final String nodeName, final String dest); static NodeOperation noop(); }### Answer:
@Test public void testAddNodeWithString() throws RepositoryException { final NodeOperation op = Ops.addNode(CHILD_NAME); op.exec(rootNode, eh); assertTrue(rootNode.hasNode(CHILD_NAME)); } |
### Question:
Ops { public static NodeOperation addProperty(final String name, final String newValue) { return new AbstractNodeOperation() { @Override protected Node doExec(Node context, ErrorHandler errorHandler) throws RepositoryException { if (context.hasProperty(name)) { throw new ItemExistsException("Property " + name + " already exists at " + context.getPath()); } final Value value = PropertyUtil.createValue(newValue, context.getSession().getValueFactory()); context.setProperty(name, value); return context; } }; } static NodeOperation addNode(final String name); static NodeOperation addNode(final String name, final String type); static NodeOperation getNode(final String name); static NodeOperation addProperty(final String name, final String newValue); static NodeOperation setProperty(final String name, final Object newValue); static NodeOperation renameNode(final String currentName, final String newName); static NodeOperation renameProperty(final String name, final String newName); static NodeOperation moveNode(final String nodeName, final String dest); static NodeOperation noop(); }### Answer:
@Test public void testAddProperty() throws Exception { final ValueFactory valueFactory = mock(ValueFactory.class); when(valueFactory.createValue(PROPERTY_VALUE)).thenReturn(new MockValue(PROPERTY_VALUE)); session.setValueFactory(valueFactory); final NodeOperation op = Ops.addProperty(PROPERTY_NAME, PROPERTY_VALUE); op.exec(rootNode, eh); assertEquals(PROPERTY_VALUE, rootNode.getProperty(PROPERTY_NAME).getString()); } |
### Question:
Ops { public static NodeOperation setProperty(final String name, final Object newValue) { return new AbstractNodeOperation() { @Override protected Node doExec(Node context, ErrorHandler errorHandler) throws RepositoryException { if (!context.hasProperty(name)) { throw new ItemNotFoundException(name); } final Value value = PropertyUtil.createValue(newValue, context.getSession().getValueFactory()); context.setProperty(name, value); return context; } }; } static NodeOperation addNode(final String name); static NodeOperation addNode(final String name, final String type); static NodeOperation getNode(final String name); static NodeOperation addProperty(final String name, final String newValue); static NodeOperation setProperty(final String name, final Object newValue); static NodeOperation renameNode(final String currentName, final String newName); static NodeOperation renameProperty(final String name, final String newName); static NodeOperation moveNode(final String nodeName, final String dest); static NodeOperation noop(); }### Answer:
@Test public void testSetProperty() throws Exception { rootNode.setProperty(PROPERTY_NAME, PROPERTY_VALUE); final String newPropertyValue = "zazoo"; final ValueFactory valueFactory = mock(ValueFactory.class); when(valueFactory.createValue(newPropertyValue)).thenReturn(new MockValue(newPropertyValue)); session.setValueFactory(valueFactory); final NodeOperation op = Ops.setProperty(PROPERTY_NAME, newPropertyValue); op.exec(rootNode, eh); assertEquals(newPropertyValue, rootNode.getProperty(PROPERTY_NAME).getString()); }
@Test(expected = RuntimeException.class) public void testSetPropertyFailsIfItsNotExistingAlready() throws Exception { final NodeOperation op = Ops.setProperty(PROPERTY_NAME, PROPERTY_VALUE); op.exec(rootNode, eh); fail("should have failed"); } |
### Question:
Ops { public static NodeOperation renameProperty(final String name, final String newName) { return new AbstractNodeOperation() { @Override protected Node doExec(Node context, ErrorHandler errorHandler) throws RepositoryException { if (!context.hasProperty(name)) { throw new ItemNotFoundException(name); } if (context.hasProperty(newName)) { throw new ItemExistsException(newName); } final Value value = context.getProperty(name).getValue(); context.setProperty(newName, value); context.getProperty(name).remove(); return context; } }; } static NodeOperation addNode(final String name); static NodeOperation addNode(final String name, final String type); static NodeOperation getNode(final String name); static NodeOperation addProperty(final String name, final String newValue); static NodeOperation setProperty(final String name, final Object newValue); static NodeOperation renameNode(final String currentName, final String newName); static NodeOperation renameProperty(final String name, final String newName); static NodeOperation moveNode(final String nodeName, final String dest); static NodeOperation noop(); }### Answer:
@Test public void testRenameProperty() throws RepositoryException { rootNode.setProperty(PROPERTY_NAME, PROPERTY_VALUE); final String newName = "newName"; final NodeOperation op = Ops.renameProperty(PROPERTY_NAME, newName); op.exec(rootNode, eh); assertTrue(!rootNode.hasProperty(PROPERTY_NAME)); assertTrue(rootNode.hasProperty(newName)); } |
### Question:
I18nNodeWrapper extends ContentDecoratorNodeWrapper { @Override public Property getProperty(String relPath) throws PathNotFoundException, RepositoryException { return wrapProperty(i18nSupport.getProperty(getWrappedNode(), relPath)); } I18nNodeWrapper(Node wrapped); @Override boolean hasProperty(String relPath); @Override Property getProperty(String relPath); }### Answer:
@Test public void testGetPropertyReturnsLocalizedValue() throws Exception { final I18nContentSupport defSupport = Components.getComponent(I18nContentSupport.class); final MockNode node = new MockNode("boo"); final I18nNodeWrapper wrappedNode = new I18nNodeWrapper(node); Property defaultblah = node.setProperty("blah", "val_blah"); Property localized = wrappedNode.getProperty("blah"); assertEquals(defaultblah.getString(), localized.getString()); Property defaultFoo = node.setProperty("foo", "val_foo"); defSupport.setLocale(new Locale("de")); localized = wrappedNode.getProperty("foo"); assertEquals(defaultFoo.getString(), localized.getString()); Property swissBlah = node.setProperty("blah_de_CH", "val_de_ch_blah"); defSupport.setLocale(new Locale("de", "CH")); localized = wrappedNode.getProperty("blah"); assertEquals(swissBlah.getString(), localized.getString()); defSupport.setLocale(new Locale("de", "AT")); localized = wrappedNode.getProperty("blah"); assertEquals(swissBlah.getString(), localized.getString()); defSupport.setLocale(new Locale("de")); localized = wrappedNode.getProperty("blah"); assertEquals(swissBlah.getString(), localized.getString()); defSupport.setLocale(new Locale("fr")); localized = wrappedNode.getProperty("blah"); assertEquals(defaultblah.getString(), localized.getString()); defSupport.setLocale(new Locale("it")); localized = wrappedNode.getProperty("blah"); assertEquals(defaultblah.getString(), localized.getString()); } |
### Question:
HTMLEscapingNodeWrapper extends ContentDecoratorNodeWrapper<HTMLEscapingContentDecorator> { @Override public String getName() throws RepositoryException { return getContentDecorator().decorate(super.getName()); } HTMLEscapingNodeWrapper(Node wrapped, final boolean transformLineBreaks); HTMLEscapingNodeWrapper(Node wrapped, HTMLEscapingContentDecorator decorator); @Override String getName(); }### Answer:
@Test public void testNodeNameIsWrappedAndEncoded() throws Exception { MockNode node = new MockNode("<html>"); HTMLEscapingNodeWrapper wrapper = new HTMLEscapingNodeWrapper(node, false); String name = wrapper.getName(); assertEquals("<html>", name); }
@Test public void testPropertyNameIsWrappedAndEncoded() throws Exception { MockNode node = new MockNode(); node.setProperty("<html>", "bla"); HTMLEscapingNodeWrapper wrapper = new HTMLEscapingNodeWrapper(node, false); assertEquals("<html>", wrapper.getProperty("<html>").getName()); }
@Test public void testNameHaveToBeEscapedBecauseOfXss() throws Exception { MockSession session = new MockSession("sessionName"); Node rootNode = session.getRootNode(); Node foo = rootNode.addNode("<>\"&"); HTMLEscapingNodeWrapper wrapper = new HTMLEscapingNodeWrapper(foo, false); String name = wrapper.getName(); assertEquals("<>"&", name); } |
### Question:
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); }### Answer:
@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()); } |
### Question:
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; }### Answer:
@Test public void testRegisterCommands() throws Exception { Catalog defaultCatalog = commandsManager.getCatalogByName("default"); assertEquals(2, getCatalogSize(defaultCatalog)); Catalog bazCatalog = commandsManager.getCatalogByName("baz"); assertEquals(2, getCatalogSize(bazCatalog)); } |
### Question:
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; }### Answer:
@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); } |
### Question:
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; }### Answer:
@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"); } |
### Question:
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; }### Answer:
@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)); } |
### Question:
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; }### Answer:
@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)); } |
### Question:
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; }### Answer:
@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)); } |
### Question:
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); }### Answer:
@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")); } |
### Question:
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(); }### Answer:
@Test public void testReturnsNullWhenValueMissing() throws Exception { RegistryMap<String, String> map = new RegistryMap<String, String>(); assertNull(map.get("key")); } |
### Question:
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(); }### Answer:
@Test(expected = RegistrationException.class) public void testThrowsExceptionWhenRequiredAndMissing() throws Exception { RegistryMap<String, String> map = new RegistryMap<String, String>(); assertEquals("value", map.getRequired("key")); } |
### Question:
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); }### Answer:
@Test public void testNoErrorIsThrownInCaseOfMissingLogConfiguration() { AuditLoggingManager mgr = new AuditLoggingManager(); try { mgr.log("test", new String[]{"NPE?"}); } catch (Throwable t) { fail("Unexepcted Exception:" + t); } } |
### Question:
HierarchyBasedI18nContentSupport extends AbstractI18nContentSupport { @Override public NodeData getNodeData(Content node, String name) { return node.getNodeData(name); } @Override NodeData getNodeData(Content node, String name); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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()); } } |
### Question:
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); }### Answer:
@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"); } } } |
### Question:
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); }### Answer:
@Test public void translatesSimpleExceptionNameProperly() { assertEquals("Path not found", ExceptionUtil.classNameToWords(new PathNotFoundException())); } |
### Question:
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); }### Answer:
@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"))); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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")); } |
### Question:
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(); }### Answer:
@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()); } |
### Question:
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(); }### Answer:
@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()); } |
### Question:
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(); }### Answer:
@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")); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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; }### Answer:
@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())); } |
### Question:
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; }### Answer:
@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)); } |
### Question:
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; }### Answer:
@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)); } |
### Question:
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; }### Answer:
@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)); } |
### Question:
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; }### Answer:
@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)); } |
### Question:
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; }### Answer:
@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)); } |
### Question:
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(); }### Answer:
@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); } |
### Question:
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(); }### Answer:
@Test public void testRuleStringConstructor() { String allowedTypes = "mgnl:resource,mgnl:contentNode,mgnl:metaData"; Rule rule = null; rule = new Rule(allowedTypes, ","); Assert.assertEquals(allowedTypes+",", rule.toString()); } |
### Question:
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(); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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()); } |
### Question:
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; }### Answer:
@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"))); } |
### Question:
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); }### Answer:
@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)); } |
### Question:
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); }### Answer:
@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")); } |
### Question:
StringLengthComparator implements Comparator<String> { @Override public int compare(String name1, String name2) { return name1.length() - name2.length(); } @Override int compare(String name1, String name2); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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/")); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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)); } |
### Question:
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); }### Answer:
@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)); } |
### Question:
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); }### Answer:
@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); } } |
### Question:
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); }### Answer:
@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()); } |
### Question:
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); }### Answer:
@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)); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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(); }### Answer:
@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()); } |
### Question:
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(); }### Answer:
@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")); } |
### Question:
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(); }### Answer:
@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()); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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; }### Answer:
@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); } |
### Question:
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); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testIsGrantedForEmptyPermissionString() { PermissionUtil.isGranted((Session) null, "ignored", ""); } |
### Question:
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(); }### Answer:
@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")); } |
### Question:
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(); }### Answer:
@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")); } |
### Question:
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(); }### Answer:
@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")); } |
### Question:
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(); }### Answer:
@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")); } |
### Question:
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); }### Answer:
@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)); } |
### Question:
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); }### Answer:
@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")); } |
### Question:
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); }### Answer:
@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)); } |
### Question:
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); } }### Answer:
@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")); } |
### Question:
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; }### Answer:
@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); } |
### Question:
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; }### Answer:
@Test public void testPasswordRemovingMethodFromURL(){ String url = "http: String url2 = "http: assertEquals(SecurityUtil.stripPasswordFromUrl(url), "http: assertEquals(SecurityUtil.stripPasswordFromUrl(url2), "http: } |
### Question:
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); }### Answer:
@Test public void testGetUserWillNotThrowErrorIfUserManagerDoesNotSupportGetUserMethod() { delegate.put("ext", externalUserManager); delegatingUserManager = new DelegatingUserManager(delegate); try { delegatingUserManager.getUser("test"); } catch (UnsupportedOperationException e) { fail("Should not fail here!"); } } |
### Question:
AccessManagerImpl implements AccessManager, Serializable { @Override public long getPermissions(String path) { if (userPermissions == null) { return Permission.NONE; } long permission = 0; int patternLength = 0; for (Permission p : userPermissions) { if (p.match(path)) { int l = p.getPattern().getLength(); if (patternLength == l && (permission < p.getPermissions())) { permission = p.getPermissions(); } else if (patternLength < l) { patternLength = l; permission = p.getPermissions(); } } } return permission; } @Override boolean isGranted(String path, long permissions); @Override void setPermissionList(List<Permission> permissions); @Override List<Permission> getPermissionList(); @Override long getPermissions(String path); }### Answer:
@Test public void testGetPermissions() { final Permission accessChildrenPermission = new PermissionImpl(); accessChildrenPermission.setPattern(new SimpleUrlPattern("/admin/test/*")); accessChildrenPermission.setPermissions(8); final List permissionList = new ArrayList(); permissionList.add(accessChildrenPermission); AccessManagerImpl ami = new AccessManagerImpl(); assertEquals(0, ami.getPermissions(TEST)); assertEquals(0, ami.getPermissions(TEST_LANG)); ami.setPermissionList(permissionList); assertEquals(0, ami.getPermissions(TEST)); assertEquals(8, ami.getPermissions(TEST_LANG)); permissionList.clear(); final Permission accessParentPermission = new PermissionImpl(); accessParentPermission.setPattern(new SimpleUrlPattern("/admin/test")); accessParentPermission.setPermissions(8); permissionList.add(accessParentPermission); assertEquals(8, ami.getPermissions(TEST)); assertEquals(0, ami.getPermissions(TEST_LANG)); permissionList.clear(); final Permission accessAllPermission = new PermissionImpl(); accessAllPermission.setPattern(new SimpleUrlPattern("/admin/test*")); accessAllPermission.setPermissions(8); permissionList.add(accessAllPermission); assertEquals(8, ami.getPermissions(TEST)); assertEquals(8, ami.getPermissions(TEST_LANG)); } |
### Question:
Security { private static void mergePrincipals(PrincipalCollectionImpl principalCollection, List<Principal> acls) { for (Principal principal : acls) { ACL princ = (ACL) principal; if (principalCollection.contains(princ.getName())) { ACL oldACL = (ACL) principalCollection.get(princ.getName()); Collection<Permission> permissions = new HashSet<Permission>(oldACL.getList()); permissions.addAll(princ.getList()); principalCollection.remove(oldACL); princ = new ACLImpl(princ.getName(), new ArrayList<Permission>(permissions)); } principalCollection.add(princ); } } static RoleManager getRoleManager(); static UserManager getUserManager(); static GroupManager getGroupManager(); static SecuritySupport getSecuritySupport(); static User getAnonymousUser(); static User getSystemUser(); static Subject getSystemSubject(); static Subject getAnonymousSubject(); }### Answer:
@Test public void testMergePrincipals() throws AccessDeniedException { Subject subject = Security.getAnonymousSubject(); assertEquals("anonymous", subject.getPrincipals(User.class).iterator().next().getName()); Iterator<PrincipalCollectionImpl> principalCollectionIter = subject.getPrincipals(PrincipalCollectionImpl.class).iterator(); Iterator<Principal> principalIter = principalCollectionIter.next().iterator(); assertEquals("website",principalIter.next().getName()); assertEquals("data",principalIter.next().getName()); assertEquals("imaging",principalIter.next().getName()); assertFalse(principalIter.hasNext()); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.