src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
ModelExecutionFilter extends OncePerRequestAbstractMgnlFilter { @Override public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { String nodeIdentifier = getIdentifierOfNodeToExecute(); if (nodeIdentifier == null) { chain.doFilter(request, response); return; } Content content = ContentUtil.asContent(getContent(nodeIdentifier)); Content orgMainContent = null; Content orgCurrentContent = null; AggregationState state = getAggregationStateSafely(); if (state != null) { orgMainContent = state.getMainContent(); orgCurrentContent = state.getCurrentContent(); state.setCurrentContent(content); if (orgMainContent == null) { state.setMainContent(content); } } try { TemplateDefinition templateDefinition = getTemplateDefinition(content.getJCRNode()); RenderingModelBasedRenderer renderingModelBasedRenderer = getRenderingModelBasedRenderer(templateDefinition); RenderingModel renderingModel; try { renderingModel = renderingModelBasedRenderer.newModel(content.getJCRNode(), templateDefinition, null); } catch (RenderException e) { throw new ServletException(e.getMessage(), e); } String actionResult; if (renderingModel instanceof EarlyExecutionAware) { actionResult = ((EarlyExecutionAware)renderingModel).executeEarly(); } else { actionResult = renderingModel.execute(); } if (handleExecutionResult(renderingModel, actionResult, templateDefinition, request, response)) { return; } MgnlContext.setAttribute(MODEL_ATTRIBUTE_PREFIX + nodeIdentifier, renderingModel); MgnlContext.setAttribute(ACTION_RESULT_ATTRIBUTE_PREFIX + nodeIdentifier, actionResult); try { chain.doFilter(request, response); } finally { MgnlContext.removeAttribute(MODEL_ATTRIBUTE_PREFIX + nodeIdentifier); MgnlContext.removeAttribute(ACTION_RESULT_ATTRIBUTE_PREFIX + nodeIdentifier); } } finally { if (state != null) { state.setMainContent(orgMainContent); state.setCurrentContent(orgCurrentContent); } } } void setAttributeName(String attributeName); @Override void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain); static final String MODEL_ATTRIBUTE_PREFIX; static final String ACTION_RESULT_ATTRIBUTE_PREFIX; static final String DEFAULT_MODEL_EXECUTION_ATTRIBUTE_NAME; }
@Test public void testWithoutParameter() throws IOException, ServletException { FilterChain chain = mock(FilterChain.class); ModelExecutionFilter filter = Components.getComponent(ModelExecutionFilter.class); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); MgnlContext.push(request, response); filter.doFilter(request, response, chain); verify(chain).doFilter(request, response); } @Test public void testExecutesRenderingModel() throws Exception { FilterChain chain = mock(FilterChain.class); ModelExecutionFilter filter = Components.getComponent(ModelExecutionFilter.class); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); setupRequestAndAggregationState(request, response, "12345"); RenderingModel renderingModel = mock(RenderingModel.class); setupRendererThatReturnsMockRenderingModel(renderingModel); filter.doFilter(request, response, chain); verify(renderingModel).execute(); verify(chain).doFilter(request, response); } @Test public void testExecutesEarlyExecutionAwareRenderingModel() throws Exception { FilterChain chain = mock(FilterChain.class); ModelExecutionFilter filter = Components.getComponent(ModelExecutionFilter.class); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); setupRequestAndAggregationState(request, response, "12345"); EarlyExecutionAware renderingModel = mock(EarlyExecutionAware.class); setupRendererThatReturnsMockRenderingModel(renderingModel); filter.doFilter(request, response, chain); verify(renderingModel).executeEarly(); verify(chain).doFilter(request, response); } @Test public void testThrowsServletExceptionWhenParameterPointsToNonExistingContent() throws Exception { FilterChain chain = mock(FilterChain.class); ModelExecutionFilter filter = Components.getComponent(ModelExecutionFilter.class); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); setupRequestAndAggregationState(request, response, "10002"); EarlyExecutionAware renderingModel = mock(EarlyExecutionAware.class); setupRendererThatReturnsMockRenderingModel(renderingModel); try { filter.doFilter(request, response, chain); fail(); } catch (ServletException e) { assertEquals("Can't read content for early execution, node: 10002", e.getMessage()); } } @Test public void testSkipsRenderingWhenRenderingModelWantsItTo() throws Exception { FilterChain chain = mock(FilterChain.class); ModelExecutionFilter filter = Components.getComponent(ModelExecutionFilter.class); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); setupRequestAndAggregationState(request, response, "12345"); EarlyExecutionAware renderingModel = mock(EarlyExecutionAware.class); when(renderingModel.executeEarly()).thenReturn(RenderingModel.SKIP_RENDERING); setupRendererThatReturnsMockRenderingModel(renderingModel); filter.doFilter(request, response, chain); verify(renderingModel).executeEarly(); verify(chain, never()).doFilter(request, response); }
RenderingModelImpl implements RenderingModel<RD> { @Override public Node getNode() { return this.content; } RenderingModelImpl(Node content, RD definition, RenderingModel<?> parent); @Override RenderingModel<?> getParent(); @Override RenderingModel<?> getRoot(); @Override Node getNode(); @Override ContentMap getContent(); RD getDef(); @Override RD getDefinition(); @Override String execute(); }
@Test public void testGetNode() { MockNode content = new MockNode(); RenderingModelImpl<ConfiguredRenderableDefinition> model = new RenderingModelImpl<ConfiguredRenderableDefinition>(content, null,null); Node result = model.getNode(); assertEquals(content, result); }
RenderingModelImpl implements RenderingModel<RD> { public RD getDef() { return getDefinition(); } RenderingModelImpl(Node content, RD definition, RenderingModel<?> parent); @Override RenderingModel<?> getParent(); @Override RenderingModel<?> getRoot(); @Override Node getNode(); @Override ContentMap getContent(); RD getDef(); @Override RD getDefinition(); @Override String execute(); }
@Test public void testGetDef() { ConfiguredRenderableDefinition definition = new ConfiguredRenderableDefinition(); RenderingModelImpl<ConfiguredRenderableDefinition> model = new RenderingModelImpl<ConfiguredRenderableDefinition>(null, definition,null); ConfiguredRenderableDefinition result = model.getDef(); assertEquals(definition, result); }
RenderingModelImpl implements RenderingModel<RD> { @Override public RD getDefinition() { return this.definition; } RenderingModelImpl(Node content, RD definition, RenderingModel<?> parent); @Override RenderingModel<?> getParent(); @Override RenderingModel<?> getRoot(); @Override Node getNode(); @Override ContentMap getContent(); RD getDef(); @Override RD getDefinition(); @Override String execute(); }
@Test public void testGetDefinition() { ConfiguredRenderableDefinition definition = new ConfiguredRenderableDefinition(); RenderingModelImpl<ConfiguredRenderableDefinition> model = new RenderingModelImpl<ConfiguredRenderableDefinition>(null, definition,null); ConfiguredRenderableDefinition result = model.getDefinition(); assertEquals(definition, result); }
RenderingModelImpl implements RenderingModel<RD> { @Override public RenderingModel<?> getRoot(){ RenderingModel<?> model = this; while(model.getParent() != null){ model = model.getParent(); } return model; } RenderingModelImpl(Node content, RD definition, RenderingModel<?> parent); @Override RenderingModel<?> getParent(); @Override RenderingModel<?> getRoot(); @Override Node getNode(); @Override ContentMap getContent(); RD getDef(); @Override RD getDefinition(); @Override String execute(); }
@Test public void testGetRoot() { RenderingModelImpl<ConfiguredRenderableDefinition> parent = new RenderingModelImpl<ConfiguredRenderableDefinition>(null, null,null); RenderingModelImpl<ConfiguredRenderableDefinition> child = new RenderingModelImpl<ConfiguredRenderableDefinition>(null, null, parent); RenderingModelImpl<ConfiguredRenderableDefinition> childOfChild = new RenderingModelImpl<ConfiguredRenderableDefinition>(null, null, child); RenderingModel<?> result = childOfChild.getRoot(); assertEquals(parent, result); }
RenderingModelImpl implements RenderingModel<RD> { @Override public String execute() { return null; } RenderingModelImpl(Node content, RD definition, RenderingModel<?> parent); @Override RenderingModel<?> getParent(); @Override RenderingModel<?> getRoot(); @Override Node getNode(); @Override ContentMap getContent(); RD getDef(); @Override RD getDefinition(); @Override String execute(); }
@Test public void testExecute() { String result = new RenderingModelImpl<ConfiguredRenderableDefinition>(null, null, null).execute(); assertNull(result); }
ConfiguredRendererProvider implements RendererProvider { @Override public Renderer getRenderer() throws RegistrationException { return renderer; } ConfiguredRendererProvider(String type, Node configNode); @Override String getType(); @Override Renderer getRenderer(); @Override String toString(); }
@Test public void testGetDefinition() throws RepositoryException, Content2BeanException, IOException, RegistrationException, Node2BeanException { Session session = SessionTestUtil.createSession(RepositoryConstants.CONFIG, "/test.class=" + TestRenderer.class.getName(), "/test.someProperty=foobar123" ); MockUtil.setSystemContextSessionAndHierarchyManager(session); ComponentsTestUtil.setImplementation(Node2BeanTransformer.class, Node2BeanTransformerImpl.class); ComponentsTestUtil.setImplementation(TypeMapping.class, TypeMappingImpl.class); ComponentsTestUtil.setImplementation(Node2BeanProcessor.class, Node2BeanProcessorImpl.class); ConfiguredRendererProvider provider = new ConfiguredRendererProvider("test", session.getNode("/test")); TestRenderer renderer = (TestRenderer) provider.getRenderer(); assertEquals("foobar123", renderer.getSomeProperty()); }
AbstractRenderer implements Renderer, RenderingModelBasedRenderer { @Override public void render(RenderingContext renderingCtx, Map<String, Object> contextObjects) throws RenderException { final RenderingModel<?> parentModel = MgnlContext.getAttribute(MODEL_ATTRIBUTE); Node content = renderingCtx.getCurrentContent(); RenderableDefinition definition = renderingCtx.getRenderableDefinition(); RenderingModel<?> model = null; String actionResult = null; if (content != null) { String uuid; try { uuid = content.getIdentifier(); } catch (RepositoryException e) { throw new RenderException(e); } model = MgnlContext.getAttribute(ModelExecutionFilter.MODEL_ATTRIBUTE_PREFIX + uuid); if (model != null) { actionResult = (String) MgnlContext.getAttribute(ModelExecutionFilter.ACTION_RESULT_ATTRIBUTE_PREFIX + uuid); if (model instanceof EarlyExecutionAware) { ((EarlyExecutionAware)model).setParent(parentModel); } } } if (model == null) { model = newModel(content, definition, parentModel); if (model != null) { actionResult = model.execute(); if (RenderingModel.SKIP_RENDERING.equals(actionResult)) { return; } } } String templatePath = resolveTemplateScript(content, definition, model, actionResult); if(templatePath == null){ throw new RenderException("No template script defined for the template definition [" + definition + "]"); } final Map<String, Object> ctx = newContext(); final Map<String, Object> savedContextState = saveContextState(ctx); setupContext(ctx, content, definition, model, actionResult); ctx.putAll(contextObjects); MgnlContext.setAttribute(MODEL_ATTRIBUTE, model); content = wrapNodeForModel(content); renderingCtx.push(content, definition); try { onRender(content, definition, renderingCtx, ctx, templatePath); } finally { renderingCtx.pop(); } MgnlContext.setAttribute(MODEL_ATTRIBUTE, parentModel); restoreContext(ctx, savedContextState); } @Override void render(RenderingContext renderingCtx, Map<String, Object> contextObjects); @Override RenderingModel<?> newModel(final Node content, final RenderableDefinition definition, final RenderingModel<?> parentModel); Map<String, ContextAttributeConfiguration> getContextAttributes(); void setContextAttributes(Map<String, ContextAttributeConfiguration> contextAttributes); void addContextAttribute(String name, ContextAttributeConfiguration contextAttributeConfiguration); }
@Test(expected = RenderException.class) public void testRenderWhenGetIdentifierThrowsException() throws RepositoryException, RenderException { Node content = mock(Node.class); doThrow(new RepositoryException()).when(content).getIdentifier(); AbstractRenderer renderer = new DummyRenderer(); when(ctx.getCurrentContent()).thenReturn(content); renderer.render(ctx, null); } @Test(expected=RenderException.class) public void testRenderWithTemplateScriptBeingNull() throws Exception { Map<String, Object> contextObjects = new LinkedHashMap<String, Object>(); RenderableDefinition definition = mock(RenderableDefinition.class); when(definition.getModelClass()).thenReturn(DummyModel.class); when(ctx.getCurrentContent()).thenReturn(content); when(ctx.getRenderableDefinition()).thenReturn(definition); AbstractRenderer renderer = new DummyRenderer() { @Override protected String resolveTemplateScript(Node content, RenderableDefinition definition, RenderingModel<?> model, String actionResult) { return null; } }; renderer.render(ctx, contextObjects); } @Test public void testRenderWithModelAttributePrefixBeingNullAndRenderingSkipped() throws Exception { RenderableDefinition definition = mock(RenderableDefinition.class); when(definition.getModelClass()).thenReturn(SkipRenderingDummyModel.class); when(ctx.getCurrentContent()).thenReturn(content); when(ctx.getRenderableDefinition()).thenReturn(definition); AbstractRenderer renderer = new DummyRenderer() { @Override protected String resolveTemplateScript(Node content, RenderableDefinition definition, RenderingModel<?> model, String actionResult) { throw new RuntimeException("Should have exited method before this call!"); } }; renderer.render(ctx, null); } @Test public void testRender() throws Exception { Map<String, Object> contextObjects = new LinkedHashMap<String, Object>(); RenderableDefinition definition = mock(RenderableDefinition.class); when(definition.getModelClass()).thenReturn(DummyModel.class); when(ctx.getCurrentContent()).thenReturn(content); when(ctx.getRenderableDefinition()).thenReturn(definition); DummyRenderer renderer = new DummyRenderer(); renderer.render(ctx, contextObjects); assertTrue(renderer.wasOnRenderCalled()); assertEquals(parentModel, MgnlContext.getAttribute(AbstractRenderer.MODEL_ATTRIBUTE)); }
AbstractRenderer implements Renderer, RenderingModelBasedRenderer { @Override public RenderingModel<?> newModel(final Node content, final RenderableDefinition definition, final RenderingModel<?> parentModel) throws RenderException { Class clazz = definition.getModelClass(); if (clazz == null) { clazz = RenderingModelImpl.class; } final Node wrappedContent = wrapNodeForModel(content); return newModel(clazz, wrappedContent, definition, parentModel); } @Override void render(RenderingContext renderingCtx, Map<String, Object> contextObjects); @Override RenderingModel<?> newModel(final Node content, final RenderableDefinition definition, final RenderingModel<?> parentModel); Map<String, ContextAttributeConfiguration> getContextAttributes(); void setContextAttributes(Map<String, ContextAttributeConfiguration> contextAttributes); void addContextAttribute(String name, ContextAttributeConfiguration contextAttributeConfiguration); }
@Test public void testWillNotFailModelCreationWhenSquareBracketIsInQueryString() throws RenderException { Map<String, String[]> map = new HashMap<String, String[]>(); map.put("checkbox[]", new String[] { "a", "b", "c" }); map.put("param", new String[] { "value" }); map.put("number", new String[] { "10" }); when(request.getParameterMap()).thenReturn(map); DummyRenderer renderer = new DummyRenderer(); RenderableDefinition definition = mock(RenderableDefinition.class); MyDummyModel model = renderer.newModel(MyDummyModel.class, content, definition, parentModel); assertEquals("value", model.getParam()); assertEquals(10, model.getNumber()); assertArrayEquals(new String[] { "a", "b", "c" }, model.getCheckbox()); }
FreemarkerRenderer extends AbstractRenderer { @Override protected void onRender(Node content, RenderableDefinition definition, RenderingContext renderingCtx, Map<String, Object> ctx, String templateScript) throws RenderException { final Locale locale = MgnlContext.getAggregationState().getLocale(); try { AppendableWriter out = renderingCtx.getAppendable(); fmHelper.render(templateScript, locale, definition.getI18nBasename(), ctx, out); } catch (TemplateException e) { throw new RenderException(e); } catch (IOException e) { throw new RenderException(e); } } FreemarkerRenderer(); FreemarkerRenderer(FreemarkerHelper fmRenderer); FreemarkerHelper getFmHelper(); }
@Test public void testOnRender() throws Exception { final RenderingContext rctx = mock(RenderingContext.class); final AppendableWriter writer = mock(AppendableWriter.class); when(rctx.getAppendable()).thenReturn(writer); final ConfiguredRenderableDefinition rd = new ConfiguredRenderableDefinition(); final String i18nBasename = "basename"; rd.setI18nBasename(i18nBasename); renderer.onRender(null, rd, rctx, null, null); verify(renderer.getFmHelper()).render(null, null, i18nBasename, null, writer); } @Test(expected = RenderException.class) public void testOnRenderThrowsRenderExceptionOnInternalIOException() throws Exception { final RenderingContext rctx = mock(RenderingContext.class); doThrow(new IOException()).when(rctx).getAppendable(); renderer.onRender(null, null, rctx, null, null); }
DefaultRenderingEngine implements RenderingEngine { protected Renderer getRendererFor(RenderableDefinition definition) throws RenderException { final String renderType = definition.getRenderType(); if (renderType == null) { throw new RenderException("No renderType defined for definition [" + definition + "]"); } try { return rendererRegistry.getRenderer(renderType); } catch (RegistrationException e) { throw new RenderException("Can't find renderer [" + renderType + "]", e); } } protected DefaultRenderingEngine(); DefaultRenderingEngine(RendererRegistry rendererRegistry, TemplateDefinitionAssignment templateDefinitionAssignment, RenderableVariationResolver variationResolver, Provider<RenderingContext> renderingContextProvider); @Override void render(Node content, OutputProvider out); @Override void render(Node content, Map<String, Object> contextObjects, OutputProvider out); @Override void render(Node content, RenderableDefinition definition, Map<String, Object> contextObjects, OutputProvider out); @Override RenderingContext getRenderingContext(); }
@Test(expected = RenderException.class) public void testGetRendererForThrowsExceptionWhenNoneIsRegistered() throws RenderException { DefaultRenderingEngine renderingEngine = createDefaultRenderingEngine(); TemplateDefinition templateDefinition = mock(TemplateDefinition.class); when(templateDefinition.getRenderType()).thenReturn(FREEMARKER_RENDERER_TYPE); renderingEngine.getRendererFor(templateDefinition); } @Test(expected = RenderException.class) public void testGetRendererForThrowsExceptionOnUnkownRenderType() throws RenderException { final RenderableDefinition def = new ConfiguredRenderableDefinition(); DefaultRenderingEngine renderingEngine = new DefaultRenderingEngine(null, null, null, null); renderingEngine.getRendererFor(def); }
DefaultRenderingEngine implements RenderingEngine { @Override public RenderingContext getRenderingContext() { return renderingContextProvider.get(); } protected DefaultRenderingEngine(); DefaultRenderingEngine(RendererRegistry rendererRegistry, TemplateDefinitionAssignment templateDefinitionAssignment, RenderableVariationResolver variationResolver, Provider<RenderingContext> renderingContextProvider); @Override void render(Node content, OutputProvider out); @Override void render(Node content, Map<String, Object> contextObjects, OutputProvider out); @Override void render(Node content, RenderableDefinition definition, Map<String, Object> contextObjects, OutputProvider out); @Override RenderingContext getRenderingContext(); }
@Test public void testGetRenderingContextWhenNotYetSet() { final AggregationStateBasedRenderingContext renderingContext = mock(AggregationStateBasedRenderingContext.class); DefaultRenderingEngine renderingEngine = createDefaultRenderingEngine(renderingContext); RenderingContext result = renderingEngine.getRenderingContext(); assertEquals(renderingContext, result); }
DefaultRenderingEngine implements RenderingEngine { @Override public void render(Node content, OutputProvider out) throws RenderException { render(content, EMPTY_CONTEXT, out); } protected DefaultRenderingEngine(); DefaultRenderingEngine(RendererRegistry rendererRegistry, TemplateDefinitionAssignment templateDefinitionAssignment, RenderableVariationResolver variationResolver, Provider<RenderingContext> renderingContextProvider); @Override void render(Node content, OutputProvider out); @Override void render(Node content, Map<String, Object> contextObjects, OutputProvider out); @Override void render(Node content, RenderableDefinition definition, Map<String, Object> contextObjects, OutputProvider out); @Override RenderingContext getRenderingContext(); }
@Test public void testRenderFromNodeAndAppendable() throws Exception { final Node content = new MockNode("parent"); RendererRegistry rendererRegistry = new RendererRegistry(); TemplateDefinitionAssignment templateDefinitionAssignment = mock(TemplateDefinitionAssignment.class); RenderingContext renderingCtx = mock(RenderingContext.class); DefaultRenderingEngine renderingEngine = createDefaultRenderingEngine(rendererRegistry, templateDefinitionAssignment, renderingCtx); TemplateDefinition templateDefinition = mock(TemplateDefinition.class); when(templateDefinitionAssignment.getAssignedTemplateDefinition(content)).thenReturn(templateDefinition); Renderer freemarkerRenderer = mock(Renderer.class); RendererProvider freemarkerRendererProvider = mock(RendererProvider.class); when(freemarkerRendererProvider.getType()).thenReturn(FREEMARKER_RENDERER_TYPE); when(freemarkerRendererProvider.getRenderer()).thenReturn(freemarkerRenderer); rendererRegistry.register(freemarkerRendererProvider); final StringBuilder builder = new StringBuilder(); OutputProvider builderWrapper = new AppendableOnlyOutputProvider(builder); final AppendableWriter writer = new AppendableWriter(builder); when(renderingCtx.getAppendable()).thenReturn(writer); when(templateDefinition.getRenderType()).thenReturn(FREEMARKER_RENDERER_TYPE); renderingEngine.render(content, builderWrapper); verify(freemarkerRenderer).render(renderingCtx, DefaultRenderingEngine.EMPTY_CONTEXT); } @Test public void testRenderThrowsRenderExceptionAndTheExceptionHandlerIsInvocedInCaseOfInternalIOException() throws Exception { final Node content = new MockNode("parent"); RendererRegistry rendererRegistry = new RendererRegistry(); TemplateDefinitionAssignment templateDefinitionAssignment = mock(TemplateDefinitionAssignment.class); RenderingContext renderingCtx = mock(RenderingContext.class); DefaultRenderingEngine renderingEngine = createDefaultRenderingEngine(rendererRegistry, templateDefinitionAssignment, renderingCtx); TemplateDefinition templateDefinition = mock(TemplateDefinition.class); when(templateDefinitionAssignment.getAssignedTemplateDefinition(content)).thenReturn(templateDefinition); Renderer freemarkerRenderer = mock(Renderer.class); RendererProvider freemarkerRendererProvider = mock(RendererProvider.class); when(freemarkerRendererProvider.getType()).thenReturn(FREEMARKER_RENDERER_TYPE); when(freemarkerRendererProvider.getRenderer()).thenReturn(freemarkerRenderer); rendererRegistry.register(freemarkerRendererProvider); final StringBuilder builder = new StringBuilder(); OutputProvider builderWrapper = new AppendableOnlyOutputProvider(builder); final AppendableWriter writer = new AppendableWriter(builder); when(renderingCtx.getAppendable()).thenReturn(writer); when(templateDefinition.getRenderType()).thenReturn(FREEMARKER_RENDERER_TYPE); final RenderException renderException = new RenderException("oh - oh!"); doThrow(renderException).when(freemarkerRenderer).render(renderingCtx, DefaultRenderingEngine.EMPTY_CONTEXT); doThrow(new IOException()).when(renderingCtx).getAppendable(); renderingEngine.render(content, builderWrapper); verify(renderingCtx).handleException(renderException); } @Test(expected = RenderException.class) public void testRenderThrowsRenderExceptionInCaseOfInternalRegistrationException() throws Exception { final Node content = new MockNode("parent"); TemplateDefinitionAssignment templateDefinitionAssignment = mock(TemplateDefinitionAssignment.class); DefaultRenderingEngine renderingEngine = createDefaultRenderingEngine(templateDefinitionAssignment, mock(RenderingContext.class)); doThrow(new RegistrationException("test")).when(templateDefinitionAssignment).getAssignedTemplateDefinition( content); renderingEngine.render(content, null); } @Test public void testRenderExceptionHandlerIsInvokedOnRenderException() throws Exception { final Node content = new MockNode("parent"); RendererRegistry rendererRegistry = new RendererRegistry(); TemplateDefinitionAssignment templateDefinitionAssignment = mock(TemplateDefinitionAssignment.class); RenderingContext renderingCtx = mock(RenderingContext.class); DefaultRenderingEngine renderingEngine = createDefaultRenderingEngine(rendererRegistry, templateDefinitionAssignment, renderingCtx); TemplateDefinition templateDefinition = mock(TemplateDefinition.class); when(templateDefinitionAssignment.getAssignedTemplateDefinition(content)).thenReturn(templateDefinition); Renderer freemarkerRenderer = mock(Renderer.class); RendererProvider freemarkerRendererProvider = mock(RendererProvider.class); when(freemarkerRendererProvider.getType()).thenReturn(FREEMARKER_RENDERER_TYPE); when(freemarkerRendererProvider.getRenderer()).thenReturn(freemarkerRenderer); rendererRegistry.register(freemarkerRendererProvider); final StringBuilder builder = new StringBuilder(); OutputProvider builderWrapper = new AppendableOnlyOutputProvider(builder); final AppendableWriter writer = new AppendableWriter(builder); when(renderingCtx.getAppendable()).thenReturn(writer); when(templateDefinition.getRenderType()).thenReturn(FREEMARKER_RENDERER_TYPE); final RenderException e = new RenderException("TEST!"); doThrow(e).when(freemarkerRenderer).render(renderingCtx, DefaultRenderingEngine.EMPTY_CONTEXT); renderingEngine.render(content, builderWrapper); verify(renderingCtx).handleException(e); }
RenderingFilter extends AbstractMgnlFilter { @Override public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException{ final AggregationState aggregationState = MgnlContext.getAggregationState(); String templateName = aggregationState.getTemplateName(); if (StringUtils.isNotEmpty(templateName)) { try { if (response != MgnlContext.getWebContext().getResponse()) { log.warn("Context response not synced. This may lead to discrepancies in rendering."); } Node content = aggregationState.getMainContent().getJCRNode(); if (!isVisible(content, request, response, aggregationState)) { if (!response.isCommitted()) { response.sendError(HttpServletResponse.SC_NOT_FOUND); } else { log.info("Unable to redirect to 404 page for {}, response is already committed", request.getRequestURI()); } return; } render(content, templateName, response); try { response.flushBuffer(); } catch (IOException e) { log.debug("Exception flushing response " + e.getClass().getName() + ": " + e.getMessage(), e); } } catch (RenderException e) { log.error(e.getMessage(), e); throw new ServletException(e); } catch (Exception e) { log.error(e.getMessage(), e); if (!response.isCommitted()) { response.setContentType("text/html"); } throw new RuntimeException(e); } } else { handleResourceRequest(aggregationState, request, response); } } RenderingFilter(RenderingEngine renderingEngine, TemplateDefinitionRegistry templateDefinitionRegistry); @Override void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain); }
@Test public void testDoFilterWithNullTemplateName() throws Exception { MgnlContext.setInstance(new MockWebContext()); RenderingFilter filter = new RenderingFilter(renderingEngine, templateDefinitionRegistry); filter.doFilter(request, response, chain); verify(response).sendError(HttpServletResponse.SC_NOT_FOUND); } @Test public void testDoFilter() throws Exception { MockWebContext context = new MockWebContext(); AggregationState aggState = new AggregationState(); aggState.setTemplateName(TEMPLATE_NAME); aggState.setMainContent(mock(Content.class)); context.setAggregationState(aggState); MgnlContext.setInstance(context); TemplateDefinitionProvider provider = mock(TemplateDefinitionProvider.class); when(provider.getId()).thenReturn(TEMPLATE_NAME); templateDefinitionRegistry.register(provider); RenderingFilter filter = new RenderingFilter(renderingEngine, templateDefinitionRegistry); filter.doFilter(request, response, chain); verify(response).flushBuffer(); verify(renderingEngine).render((Node) anyObject(), (RenderableDefinition) anyObject(), (Map) anyObject(), (OutputProvider) anyObject()); } @Test(expected = ServletException.class) public void testDoFilterThrowsServletExceptionOnMissingTemplateDefinitionProvider() throws Exception { AggregationState aggState = new AggregationState(); aggState.setTemplateName(TEMPLATE_NAME); aggState.setMainContent(mock(Content.class)); MockWebContext context = new MockWebContext(); context.setAggregationState(aggState); MgnlContext.setInstance(context); RenderingFilter filter = new RenderingFilter(renderingEngine, templateDefinitionRegistry); filter.doFilter(request, response, chain); } @Test public void testDoFilterWhenTemplateIsNotRegistered() throws Exception { RenderingFilter filter = new RenderingFilter(renderingEngine, templateDefinitionRegistry); MockWebContext context = new MockWebContext(); AggregationState aggState = new AggregationState(); context.setAggregationState(aggState); MgnlContext.setInstance(context); filter.doFilter(request, response, chain); verify(response).sendError(HttpServletResponse.SC_NOT_FOUND); }
RenderingFilter extends AbstractMgnlFilter { protected void handleResourceRequest(AggregationState aggregationState, HttpServletRequest request, HttpServletResponse response) throws IOException { final String resourceHandle = aggregationState.getHandle(); log.debug("handleResourceRequest, resourceHandle=\"{}\"", resourceHandle); if (StringUtils.isNotEmpty(resourceHandle)) { InputStream is = null; try { Session session = MgnlContext.getJCRSession(aggregationState.getRepository()); is = getNodedataAsStream(resourceHandle, session, response); if (null != is) { sendUnCompressed(is, response); IOUtils.closeQuietly(is); return; } } catch (IOException e) { log.debug("Exception while dispatching resource " + e.getClass().getName() + ": " + e.getMessage(), e); return; } catch (Exception e) { log.error("Exception while dispatching resource " + e.getClass().getName() + ": " + e.getMessage(), e); return; } finally { IOUtils.closeQuietly(is); } } log.debug("Resource not found, redirecting request for [{}] to 404 URI", request.getRequestURI()); if (!response.isCommitted()) { response.sendError(HttpServletResponse.SC_NOT_FOUND); } else { log.info("Unable to redirect to 404 page for {}, response is already committed", request.getRequestURI()); } } RenderingFilter(RenderingEngine renderingEngine, TemplateDefinitionRegistry templateDefinitionRegistry); @Override void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain); }
@Test public void testHandleResourceRequest() throws Exception { String contentProperties = StringUtils.join(Arrays.asList( "/first/attachment2.@type=mgnl:resource", "/first/attachment2.fileName=test", "/first/attachment2.extension=jpeg", "/first/attachment2.jcr\\:data=binary:X", "/first/attachment2.jcr\\:mimeType=image/jpeg", "/first/attachment2.size=1" ), "\n"); final String first = "first"; MockSession session = SessionTestUtil.createSession("testWorkspace", contentProperties); final String binaryNodeName = "attachment2"; AggregationState aggState = new AggregationState(); aggState.setHandle("/" + first + "/" + binaryNodeName); final String repository = "testRepository"; aggState.setRepository(repository); WebContext context = mock(WebContext.class); MgnlContext.setInstance(context); when(context.getJCRSession(repository)).thenReturn(session); MockServletOutputStream outputStream = new MockServletOutputStream(); when(response.getOutputStream()).thenReturn(outputStream); RenderingFilter filter = new RenderingFilter(renderingEngine, templateDefinitionRegistry); filter.handleResourceRequest(aggState, request, response); verify(response).setContentLength(1); assertEquals("X", outputStream.getContent()); } @Test public void testHandleResourceRequestWhenNoJCRDataIsAvailable() throws Exception { String contentProperties = StringUtils.join(Arrays.asList( "/first/attachment2.@type=mgnl:resource", "/first/attachment2.fileName=test", "/first/attachment2.extension=jpeg", "/first/attachment2.jcr\\:mimeType=image/jpeg", "/first/attachment2.size=1" ), "\n"); final String first = "first"; MockSession session = SessionTestUtil.createSession("testWorkspace", contentProperties); final String binaryNodeName = "attachment2"; AggregationState aggState = new AggregationState(); aggState.setHandle("/" + first + "/" + binaryNodeName); final String repository = "testRepository"; aggState.setRepository(repository); WebContext context = mock(WebContext.class); MgnlContext.setInstance(context); when(context.getJCRSession(repository)).thenReturn(session); MockServletOutputStream outputStream = new MockServletOutputStream(); when(response.getOutputStream()).thenReturn(outputStream); RenderingFilter filter = new RenderingFilter(renderingEngine, templateDefinitionRegistry); filter.handleResourceRequest(aggState, request, response); verify(response).sendError(HttpServletResponse.SC_NOT_FOUND); assertEquals("", outputStream.getContent()); }
ModeDependentRenderExceptionHandler implements RenderExceptionHandler { @Override public void handleException(RenderException renderException, RenderingContext renderingContext) { String path; try { path = renderingContext.getCurrentContent().getPath(); } catch (RepositoryException e) { path = "Can't read content"; } String id = renderingContext.getRenderableDefinition().getId(); PrintWriter out; try { out = getPrintWriterFor(renderingContext.getAppendable()); String msg = "Error while rendering [" + path + "] with template ["+id+"]: " + ExceptionUtils.getMessage(renderException); if ( serverConfiguration.isAdmin() && !MgnlContext.getAggregationState().isPreviewMode()) { inEditMode(msg, renderException, out); } else { inPublicMode(msg, renderException, out); } } catch (IOException e) { throw new RuntimeException("Can't log template exception.", e); } out.flush(); } @Inject ModeDependentRenderExceptionHandler(ServerConfiguration config); @Override void handleException(RenderException renderException, RenderingContext renderingContext); static final String RENDER_ERROR_MESSAGE_BEGIN; static final String RENDER_ERROR_MESSAGE_END; }
@Test public void testOnlyExceptionGetsFlushedInPublicMode() throws IOException { final RenderException ex = mock(RenderException.class); final ServerConfiguration serverConfig = new ServerConfiguration(); serverConfig.setAdmin(false); ModeDependentRenderExceptionHandler handler = new ModeDependentRenderExceptionHandler(serverConfig); handler.handleException(ex, renderingContext); verify(ex).printStackTrace((PrintWriter) any()); verify(out).flush(); } @Test public void testOnlyExceptionGetsFlushedInAdminPreviewMode() throws IOException { final RenderException ex = mock(RenderException.class); final ServerConfiguration serverConfig = new ServerConfiguration(); serverConfig.setAdmin(true); MgnlContext.getAggregationState().setPreviewMode(true); ModeDependentRenderExceptionHandler handler = new ModeDependentRenderExceptionHandler(serverConfig); handler.handleException(ex, renderingContext); verify(ex).printStackTrace((PrintWriter) any()); verify(out).flush(); } @Test public void testExceptionAndAdditionalMessageGetsFlushedAdminNonPreviewMode() throws IOException{ final RenderException ex = mock(RenderException.class); final ServerConfiguration serverConfig = new ServerConfiguration(); serverConfig.setAdmin(true); MgnlContext.getAggregationState().setPreviewMode(false); ModeDependentRenderExceptionHandler handler = new ModeDependentRenderExceptionHandler(serverConfig); handler.handleException(ex, renderingContext); verify(out).write(ModeDependentRenderExceptionHandler.RENDER_ERROR_MESSAGE_BEGIN, 0, ModeDependentRenderExceptionHandler.RENDER_ERROR_MESSAGE_BEGIN.length()); verify(ex).printStackTrace((PrintWriter) any()); verify(out).write(ModeDependentRenderExceptionHandler.RENDER_ERROR_MESSAGE_END, 0, ModeDependentRenderExceptionHandler.RENDER_ERROR_MESSAGE_END.length()); verify(out).flush(); }
AggregationStateBasedRenderingContext implements RenderingContext { @Override public Node getMainContent() { Content mainContent = aggregationState.getMainContent(); return mainContent != null ? mainContent.getJCRNode() : null; } @Inject AggregationStateBasedRenderingContext(Provider<AggregationState> aggregationStateProvider, RenderExceptionHandler exceptionHandler); AggregationStateBasedRenderingContext(AggregationState aggregationState, RenderExceptionHandler exceptionHandler); @Override Node getMainContent(); @Override Node getCurrentContent(); @Override RenderableDefinition getRenderableDefinition(); @Override void push(Node content, RenderableDefinition renderableDefinition); @Override void push(Node content, RenderableDefinition renderableDefinition, OutputProvider outputProvider); @Override void pop(); @Override OutputProvider getOutputProvider(); @Override AppendableWriter getAppendable(); @Override OutputStream getOutputStream(); @Override void handleException(RenderException renderException); }
@Test public void usesAggregationStateFromProvider() throws Exception { aggregationState.setMainContent(mainContent); context = new AggregationStateBasedRenderingContext(Providers.of(aggregationState), null); Node returnedMainContent = context.getMainContent(); assertSame(mainNode, returnedMainContent); } @Test public void testGetMainContent() { aggregationState.setMainContent(mainContent); Node result = context.getMainContent(); assertEquals(mainNode, result); }
AggregationStateBasedRenderingContext implements RenderingContext { @Override public Node getCurrentContent() { Content currentContent = aggregationState.getCurrentContent(); return currentContent != null ? currentContent.getJCRNode() : null; } @Inject AggregationStateBasedRenderingContext(Provider<AggregationState> aggregationStateProvider, RenderExceptionHandler exceptionHandler); AggregationStateBasedRenderingContext(AggregationState aggregationState, RenderExceptionHandler exceptionHandler); @Override Node getMainContent(); @Override Node getCurrentContent(); @Override RenderableDefinition getRenderableDefinition(); @Override void push(Node content, RenderableDefinition renderableDefinition); @Override void push(Node content, RenderableDefinition renderableDefinition, OutputProvider outputProvider); @Override void pop(); @Override OutputProvider getOutputProvider(); @Override AppendableWriter getAppendable(); @Override OutputStream getOutputStream(); @Override void handleException(RenderException renderException); }
@Test public void testGetCurrentContent() { aggregationState.setCurrentContent(mainContent); Node result = context.getCurrentContent(); assertEquals(mainNode, result); }
AggregationStateBasedRenderingContext implements RenderingContext { @Override public void pop() { if (depth == 0) { throw new EmptyStackException(); } else if (depth == 1) { aggregationState.setCurrentContent(null); currentRenderableDefinition = null; currentOutputProvider = null; } else { StackState state = stack.pop(); aggregationState.setCurrentContent(state.legacyContent); currentRenderableDefinition = state.renderableDefinition; currentOutputProvider = state.outputProvider; } depth--; } @Inject AggregationStateBasedRenderingContext(Provider<AggregationState> aggregationStateProvider, RenderExceptionHandler exceptionHandler); AggregationStateBasedRenderingContext(AggregationState aggregationState, RenderExceptionHandler exceptionHandler); @Override Node getMainContent(); @Override Node getCurrentContent(); @Override RenderableDefinition getRenderableDefinition(); @Override void push(Node content, RenderableDefinition renderableDefinition); @Override void push(Node content, RenderableDefinition renderableDefinition, OutputProvider outputProvider); @Override void pop(); @Override OutputProvider getOutputProvider(); @Override AppendableWriter getAppendable(); @Override OutputStream getOutputStream(); @Override void handleException(RenderException renderException); }
@Test public void testPop() throws Exception { Node second = mock(Node.class); when(second.getSession()).thenReturn(session); RenderableDefinition firstRenderableDefinition = mock(RenderableDefinition.class); RenderableDefinition secondRenderableDefinition = mock(RenderableDefinition.class); context.push(mainNode, firstRenderableDefinition, null); context.push(second, secondRenderableDefinition, null); context.pop(); assertEquals(mainNode, context.getCurrentContent()); assertEquals(firstRenderableDefinition, context.getRenderableDefinition()); } @Test(expected = EmptyStackException.class) public void testPopWithoutPrecedingPush() { context.pop(); }
AggregationStateBasedRenderingContext implements RenderingContext { @Override public RenderableDefinition getRenderableDefinition() { return currentRenderableDefinition; } @Inject AggregationStateBasedRenderingContext(Provider<AggregationState> aggregationStateProvider, RenderExceptionHandler exceptionHandler); AggregationStateBasedRenderingContext(AggregationState aggregationState, RenderExceptionHandler exceptionHandler); @Override Node getMainContent(); @Override Node getCurrentContent(); @Override RenderableDefinition getRenderableDefinition(); @Override void push(Node content, RenderableDefinition renderableDefinition); @Override void push(Node content, RenderableDefinition renderableDefinition, OutputProvider outputProvider); @Override void pop(); @Override OutputProvider getOutputProvider(); @Override AppendableWriter getAppendable(); @Override OutputStream getOutputStream(); @Override void handleException(RenderException renderException); }
@Test public void testGetRenderableDefinition() throws Exception { Node second = mock(Node.class); when(second.getSession()).thenReturn(session); RenderableDefinition firstRenderableDefinition = mock(RenderableDefinition.class); RenderableDefinition secondRenderableDefinition = mock(RenderableDefinition.class); context.push(mainNode, firstRenderableDefinition, null); context.push(second, secondRenderableDefinition, null); RenderableDefinition result = context.getRenderableDefinition(); assertEquals(result, secondRenderableDefinition); } @Test public void testGetRenderableDefinitionBeforePushReturnsNull() { RenderableDefinition result = context.getRenderableDefinition(); assertNull(result); }
RenderingModule implements ModuleLifecycle { @Override public void start(ModuleLifecycleContext moduleLifecycleContext) { templateDefinitionManager.start(); rendererManager.start(); } @Inject RenderingModule(ConfiguredTemplateDefinitionManager templateDefinitionManager, ConfiguredRendererManager rendererManager); @Override void start(ModuleLifecycleContext moduleLifecycleContext); @Override void stop(ModuleLifecycleContext moduleLifecycleContext); }
@Test public void testStartsManagers() { ConfiguredTemplateDefinitionManager configuredTemplateDefinitionManager = mock(ConfiguredTemplateDefinitionManager.class); ConfiguredRendererManager configuredRendererManager = mock(ConfiguredRendererManager.class); RenderingModule renderingModule = new RenderingModule(configuredTemplateDefinitionManager, configuredRendererManager); renderingModule.start(mock(ModuleLifecycleContext.class)); verify(configuredTemplateDefinitionManager).start(); verify(configuredRendererManager).start(); }
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); }
@Test(expected = RegistrationException.class) public void testGetTemplateDefinitionThrowsOnBadId() throws RegistrationException { TemplateDefinitionRegistry registry = new TemplateDefinitionRegistry(); registry.getTemplateDefinition("nonExistingId"); }
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); }
@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()); }
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); }
@Test public void testAvailableComponentsIsInitiallyEmpty() { ConfiguredAreaDefinition def = new ConfiguredAreaDefinition(); int componentsSize = def.getAvailableComponents().size(); assertEquals(0, componentsSize); }
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); }
@Test public void testSetAvailableComponents() { ConfiguredAreaDefinition def = new ConfiguredAreaDefinition(); Map<String, ComponentAvailability> newMap = Collections.<String, ComponentAvailability> emptyMap(); def.setAvailableComponents(newMap); assertEquals(newMap, def.getAvailableComponents()); }
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); }
@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); }
MetaDataBasedTemplateDefinitionAssignment implements TemplateDefinitionAssignment { @Override public Collection<TemplateDefinition> getAvailableTemplates(Node content) { try { if (content != null && NodeUtil.hasMixin(content, NodeTypes.Deleted.NAME)) { return Collections.singleton(templateDefinitionRegistry.getTemplateDefinition(DELETED_PAGE_TEMPLATE)); } } catch (RepositoryException e) { log.error("Failed to check node for deletion status.", e); } catch (RegistrationException e) { log.error("Deleted content template is not correctly registered.", e); } final ArrayList<TemplateDefinition> availableTemplateDefinitions = new ArrayList<TemplateDefinition>(); final Collection<TemplateDefinition> templateDefinitions = templateDefinitionRegistry.getTemplateDefinitions(); for (TemplateDefinition templateDefinition : templateDefinitions) { if (isTemplateAvailable(content, templateDefinition)) { availableTemplateDefinitions.add(templateDefinition); } } Collections.sort(availableTemplateDefinitions, new Comparator<TemplateDefinition>() { @Override public int compare(TemplateDefinition lhs, TemplateDefinition rhs) { return getI18nTitle(lhs).compareTo(getI18nTitle(rhs)); } private String getI18nTitle(TemplateDefinition templateDefinition) { Messages messages = MessagesManager.getMessages(templateDefinition.getI18nBasename()); return messages.getWithDefault(templateDefinition.getTitle(), templateDefinition.getTitle()); } }); return availableTemplateDefinitions; } @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); }
@Test public void testGetAvailableTemplatesForDeletedNode() { TemplateDefinitionRegistry registry = new TemplateDefinitionRegistry(); MetaDataBasedTemplateDefinitionAssignment assignment = new MetaDataBasedTemplateDefinitionAssignment(registry); TemplateDefinition deletedTemplate = mock(TemplateDefinition.class); registry.register(new SimpleTemplateDefinitionProvider("adminInterface:mgnlDeleted", deletedTemplate)); registry.register(new SimpleTemplateDefinitionProvider("some:other/template/that/wont/be/returned", mock(TemplateDefinition.class))); MockNode mockNode = new MockNode(); mockNode.addMixin(NodeTypes.Deleted.NAME); Collection<TemplateDefinition> availableTemplates = assignment.getAvailableTemplates(mockNode); assertEquals(1, availableTemplates.size()); assertSame(deletedTemplate, availableTemplates.iterator().next()); } @Test public void testGetAvailableTemplatesReturnsOnlyVisibleTemplates() { MockUtil.initMockContext(); MockSession session = new MockSession(new MockWorkspace("website")); MockUtil.setSessionAndHierarchyManager(session); TemplateDefinitionRegistry registry = new TemplateDefinitionRegistry(); MetaDataBasedTemplateDefinitionAssignment assignment = new MetaDataBasedTemplateDefinitionAssignment(registry); MockNode mockNode = new MockNode(session); TemplateDefinition visibleTemplate = mock(TemplateDefinition.class); when(visibleTemplate.getVisible()).thenReturn(Boolean.TRUE); when(visibleTemplate.getId()).thenReturn("module:pages/visibleTemplate"); registry.register(new SimpleTemplateDefinitionProvider("module:pages/visibleTemplate", visibleTemplate)); TemplateDefinition invisibleTemplate = mock(TemplateDefinition.class); when(invisibleTemplate.getVisible()).thenReturn(Boolean.FALSE); when(invisibleTemplate.getId()).thenReturn("module:pages/invisibleTemplate"); registry.register(new SimpleTemplateDefinitionProvider("module:pages/invisibleTemplate", invisibleTemplate)); Collection<TemplateDefinition> availableTemplates = assignment.getAvailableTemplates(mockNode); assertEquals(1, availableTemplates.size()); assertSame(visibleTemplate, availableTemplates.iterator().next()); }
MetaDataBasedTemplateDefinitionAssignment implements TemplateDefinitionAssignment { @Override public TemplateDefinition getDefaultTemplate(Node content) { TemplateDefinition parentTemplate = null; try { parentTemplate = getAssignedTemplateDefinition(content.getParent()); } catch (RepositoryException e) { log.error("Failed to determine template assigned to parent of node: " + NodeUtil.getNodePathIfPossible(content), e); } catch (RegistrationException e) { } if (parentTemplate != null && isAvailable(content, parentTemplate)) { return parentTemplate; } Collection<TemplateDefinition> templates = getAvailableTemplates(content); if (templates.isEmpty()) { return null; } return templates.iterator().next(); } @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); }
@Test public void testGetDefaultTemplateUsesTemplateFromParent() throws RepositoryException { MockUtil.initMockContext(); MockSession session = new MockSession(new MockWorkspace("website")); MockUtil.setSessionAndHierarchyManager(session); TemplateDefinitionRegistry registry = new TemplateDefinitionRegistry(); MetaDataBasedTemplateDefinitionAssignment assignment = new MetaDataBasedTemplateDefinitionAssignment(registry); Node parentNode = session.getRootNode(); parentNode.addMixin(NodeTypes.Renderable.NAME); NodeTypes.Renderable.set(parentNode, "module:pages/template1"); Node mockNode = parentNode.addNode("child"); TemplateDefinition template1 = mock(TemplateDefinition.class); when(template1.getVisible()).thenReturn(Boolean.TRUE); when(template1.getId()).thenReturn("module:pages/template1"); registry.register(new SimpleTemplateDefinitionProvider("module:pages/template1", template1)); TemplateDefinition template2 = mock(TemplateDefinition.class); when(template2.getVisible()).thenReturn(Boolean.TRUE); when(template2.getId()).thenReturn("module:pages/template2"); registry.register(new SimpleTemplateDefinitionProvider("module:pages/template2", template2)); assertSame(template1, assignment.getDefaultTemplate(mockNode)); NodeTypes.Renderable.set(parentNode, "module:pages/template2"); assertSame(template2, assignment.getDefaultTemplate(mockNode)); }
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); }
@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); }
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); }
@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); }
DefaultRenderableVariationResolver implements RenderableVariationResolver { @Override public RenderableDefinition resolveVariation(RenderableDefinition renderableDefinition) { AggregationState aggregationState = getAggregationStateSafely(); if (aggregationState == null) { return null; } final String channelName = aggregationState.getChannel().getName(); final String extensionName = aggregationState.getExtension(); final String channelExtensionName = channelName + "-" + extensionName; RenderableDefinition defVariation = renderableDefinition.getVariations().get(channelExtensionName); if (defVariation != null) { return BeanMergerUtil.merge(defVariation, renderableDefinition); } defVariation = renderableDefinition.getVariations().get(extensionName); if (defVariation != null) { return BeanMergerUtil.merge(defVariation, renderableDefinition); } defVariation = renderableDefinition.getVariations().get(channelName); if (defVariation != null) { return BeanMergerUtil.merge(defVariation, renderableDefinition); } return null; } @Override RenderableDefinition resolveVariation(RenderableDefinition renderableDefinition); }
@Test public void testChooseTemplateWhenVariationExistForChannelExtensionName() throws Exception { final MockWebContext mockContext = (MockWebContext) MockUtil.initMockContext(); final Channel channel = new Channel(); channel.setName(CHANNEL); mockContext.getAggregationState().setChannel(channel); mockContext.getAggregationState().setExtension(EXTENSION); final DefaultRenderableVariationResolver resolver = new DefaultRenderableVariationResolver(); RenderableDefinition result = resolver.resolveVariation(templateDefinition); assertEquals(CHANNEL_EXTENSION, result.getName()); assertEquals("this-is-an-overriding-templateScript-for-channel-extension", result.getTemplateScript()); assertEquals("this-will-be-reused-by-the-variation", result.getDescription()); } @Test public void testChooseTemplateWhenVariationExistForExtensionName() throws Exception { final MockWebContext mockContext = (MockWebContext) MockUtil.initMockContext(); mockContext.getAggregationState().setExtension(EXTENSION); final DefaultRenderableVariationResolver resolver = new DefaultRenderableVariationResolver(); RenderableDefinition result = resolver.resolveVariation(templateDefinition); assertEquals(EXTENSION, result.getName()); assertEquals("this-is-an-overriding-templateScript-for-extension", result.getTemplateScript()); assertEquals("this-will-be-reused-by-the-variation", result.getDescription()); } @Test public void testChooseTemplateWhenVariationExistForChannelName() throws Exception { final MockWebContext mockContext = (MockWebContext) MockUtil.initMockContext(); final Channel channel = new Channel(); channel.setName(CHANNEL); mockContext.getAggregationState().setChannel(channel); final DefaultRenderableVariationResolver resolver = new DefaultRenderableVariationResolver(); RenderableDefinition result = resolver.resolveVariation(templateDefinition); assertEquals(CHANNEL, result.getName()); assertEquals("this-is-an-overriding-templateScript-for-channel", 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("channelDoesNotExist"); mockContext.getAggregationState().setChannel(channel); mockContext.getAggregationState().setExtension("extensionDoesNotExist"); final DefaultRenderableVariationResolver resolver = new DefaultRenderableVariationResolver(); RenderableDefinition result = resolver.resolveVariation(templateDefinition); assertNull(result); } @Test public void testDoesNothingWhenAggregationStateNotAvailable() throws Exception { final DefaultRenderableVariationResolver resolver = new DefaultRenderableVariationResolver(); final RenderableDefinition result = resolver.resolveVariation(templateDefinition); assertNull(result); }
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(); }
@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(); }
TemplatingFunctions { public Node asJCRNode(ContentMap contentMap) { return contentMap == null ? null : contentMap.getJCRNode(); } @Inject TemplatingFunctions(Provider<AggregationState> aggregationStateProvider); Node asJCRNode(ContentMap contentMap); ContentMap asContentMap(Node content); List<Node> children(Node content); List<Node> children(Node content, String nodeTypeName); List<ContentMap> children(ContentMap content); List<ContentMap> children(ContentMap content, String nodeTypeName); ContentMap root(ContentMap contentMap); ContentMap root(ContentMap contentMap, String nodeTypeName); Node root(Node content); Node root(Node content, String nodeTypeName); ContentMap parent(ContentMap contentMap); ContentMap parent(ContentMap contentMap, String nodeTypeName); Node parent(Node content); Node parent(Node content, String nodeTypeName); ContentMap page(ContentMap content); Node page(Node content); List<ContentMap> ancestors(ContentMap contentMap); List<ContentMap> ancestors(ContentMap contentMap, String nodeTypeName); List<Node> ancestors(Node content); List<Node> ancestors(Node content, String nodeTypeName); Node inherit(Node content); Node inherit(Node content, String relPath); ContentMap inherit(ContentMap content); ContentMap inherit(ContentMap content, String relPath); Property inheritProperty(Node content, String relPath); Property inheritProperty(ContentMap content, String relPath); List<Node> inheritList(Node content, String relPath); List<ContentMap> inheritList(ContentMap content, String relPath); boolean isInherited(Node content); boolean isInherited(ContentMap content); boolean isFromCurrentPage(Node content); boolean isFromCurrentPage(ContentMap content); String link(String workspace, String nodeIdentifier); @Deprecated String link(Property property); String link(Node content); String link(ContentMap contentMap); String language(); String externalLink(Node content, String linkPropertyName); String externalLink(ContentMap content, String linkPropertyName); String externalLinkTitle(Node content, String linkPropertyName, String linkTitlePropertyName); String externalLinkTitle(ContentMap content, String linkPropertyName, String linkTitlePropertyName); boolean isEditMode(); boolean isPreviewMode(); boolean isAuthorInstance(); boolean isPublicInstance(); String createHtmlAttribute(String name, String value); SiblingsHelper siblings(Node node); SiblingsHelper siblings(ContentMap node); Node content(String path); Node content(String repository, String path); Node contentByIdentifier(String id); Node contentByIdentifier(String repository, String id); List<ContentMap> asContentMapList(Collection<Node> nodeList); List<Node> asNodeList(Collection<ContentMap> contentMapList); ContentMap decode(ContentMap content); Node decode(Node content); Node encode(Node content); String metaData(Node content, String property); String metaData(ContentMap content, String property); Collection<Node> search(String workspace, String statement, String language, String returnItemType); Collection<Node> simpleSearch(String workspace, String statement, String returnItemType, String startPath); }
@Test public void testAsJCRNodeFromContentMap() throws RepositoryException { Node resultContenMap = functions.asJCRNode(topPageContentMap); assertNodeEqualsMap(topPageContentMap, resultContenMap); }
JspTemplatingFunction { @Function public static String link(ContentMap contentMap) throws RepositoryException { return getTemplatingFunctions().link(contentMap); } @Function static Node asJCRNode(ContentMap contentMap); @Function static ContentMap asContentMap(Node content); @Function static List<ContentMap> children(ContentMap content, String nodeTypeName); @Function() static ContentMap root(ContentMap contentMap, String nodeTypeName); @Function static ContentMap parent(ContentMap contentMap, String nodeTypeName); @Function static ContentMap page(ContentMap content); @Function static List<ContentMap> ancestors(ContentMap contentMap, String nodeTypeName); @Function static ContentMap inherit(ContentMap content, String relPath); @Function static Property inheritProperty(ContentMap content, String relPath); @Function static List<ContentMap> inheritList(ContentMap content, String relPath); @Function static boolean isInherited(ContentMap content); @Function static boolean isFromCurrentPage(ContentMap content); @Function static String linkForWorkspace(String workspace, String nodeIdentifier); @Function static String linkForProperty(Property property); @Function static String link(ContentMap contentMap); @Function static String link(ContentMap contentMap, String propertyName); @Function static String language(); @Function static String externalLink(ContentMap content, String linkPropertyName); @Function static String externalLinkTitle(ContentMap content, String linkPropertyName, String linkTitlePropertyName); @Function static boolean isEditMode(); @Function static boolean isPreviewMode(); @Function static boolean isAuthorInstance(); @Function static boolean isPublicInstance(); @Function static String createHtmlAttribute(String name, String value); @Function static SiblingsHelper siblings(ContentMap node); @Function static Node content(String path,String repository); @Function static Node contentByIdentifier(String id, String repository); @Function static List<ContentMap> asContentMapList(Collection<Node> nodeList); @Function static List<Node> asNodeList(Collection<ContentMap> contentMapList); @Function static ContentMap decode(ContentMap content); @Function static String metaData(ContentMap content, String property); @Function static Collection<Node> search(String workspace, String statement, String language, String returnItemType); @Function static Collection<Node> simpleSearch(String workspace, String statement, String returnItemType, String startPath); }
@Test public void testLink() throws Exception { BootstrapUtil.bootstrap(new String[] { "/website.01.xml" }, ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW); Node test = MgnlContext.getJCRSession("website").getRootNode().getNode("01"); ContentMap contentMap = new ContentMap(test); String link3 = LinkUtil.createLink(ContentUtil.asContent(test).getNodeData("image")); assertEquals("/01/image/Cents1-1.jpg", link3); String link = JspTemplatingFunction.linkForProperty(((ContentMap) contentMap.get("image")).getJCRNode().getProperty("jcr:data")); assertEquals("/01/image/Cents1-1.jpg", link); String link1 = JspTemplatingFunction.link((ContentMap) contentMap.get("image")); assertEquals("/01/image/Cents1-1.jpg", link1); String link2 = JspTemplatingFunction.linkForWorkspace(test.getSession().getWorkspace().getName(), test.getNode("image").getIdentifier()); assertEquals("/01/image/Cents1-1.jpg", link2); }
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(); }
@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); }
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(); }
@Test public void testShouldBeUseableWithoutAnyAttribute() throws Exception { final PoweredByTag tag = new PoweredByTag(); tag.setJspContext(pageContext); tag.doTag(); assertJspContent("Powered by <a href=\"http: }
SimpleNavigationTag extends TagSupport { @Override public int doEndTag() throws JspException { Content activePage = getCurrentActivePage(); try { while (!ItemType.PAGE.getSystemName().equals(activePage.getNodeTypeName()) && activePage.getLevel() != 0) { activePage = activePage.getParent(); } } catch (RepositoryException e) { log.error("Failed to obtain parent page for " + getCurrentActivePage().getHandle(), e); activePage = getCurrentActivePage(); } JspWriter out = this.pageContext.getOut(); if (StringUtils.isNotEmpty(this.contentFilter)) { try { filter = (ContentFilter) this.pageContext.getAttribute(this.contentFilter); } catch (ClassCastException e) { log.error("contentFilter assigned was not a content filter", e); } } else { filter = null; } if (startLevel > endLevel) { endLevel = 0; } try { final int activePageLevel = activePage.getLevel(); if (relativeLevels) { this.startLevel += activePageLevel; this.endLevel += activePageLevel; } if (this.startLevel <= activePageLevel) { Content startContent = activePage.getAncestor(this.startLevel); drawChildren(startContent, activePage, out); } } catch (RepositoryException e) { log.error("RepositoryException caught while drawing navigation: " + e.getMessage(), e); return EVAL_PAGE; } catch (IOException e) { throw new NestableRuntimeException(e); } return EVAL_PAGE; } void setStartLevel(int startLevel); void setEndLevel(int endLevel); void setStyle(String style); void setHideInNav(String hideInNav); void setOpenMenu(String openMenu); void setNofollow(String nofollow); void setContentFilter(String contentFilter); void setExpandAll(String expandAll); void setRelativeLevels(boolean relativeLevels); void setClassProperty(String classProperty); void setWrapperElement(String wrapperElement); void setMarkFirstAndLastElement(boolean flag); @Override int doEndTag(); @Override void release(); static final String NODEDATA_ACCESSKEY; static final String DEFAULT_OPENMENU_NODEDATA; static final String DEFAULT_HIDEINNAV_NODEDATA; static final String DEFAULT_WRAPPERELEMENT_NODEDATA; static final String EXPAND_ALL; static final String EXPAND_SHOW; static final String EXPAND_NONE; public String wrapperElement; }
@Test public void testChildren() throws Exception { SimpleNavigationTag tag = new SimpleNavigationTag(); Content current = mock(Content.class); Content parent = mock(Content.class); Content dummy = mock(Content.class); Content hideInNav = mock(Content.class); WebContext ctx = mock(WebContext.class); NodeData bool = mock(NodeData.class); NodeData string = mock(NodeData.class); AggregationState aggState = new AggregationState(); PageContext pageContext = new MockPageContext(new MockServletConfig(), new MockHttpServletRequest(), new MockHttpServletResponse()); MgnlContext.setInstance(ctx); when(ctx.getAggregationState()).thenReturn(aggState); aggState.setCurrentContent(current); when(current.getNodeTypeName()).thenReturn(ItemType.CONTENT.getSystemName()); tag.setPageContext(pageContext); when(current.getLevel()).thenReturn(0); when(current.getAncestor(0)).thenReturn(parent); when(parent.getChildren(ItemType.CONTENT)).thenReturn(Arrays.asList(new Content[] { dummy, hideInNav, current })); when(parent.getLevel()).thenReturn(0); when(dummy.getNodeData("hideInNav")).thenReturn(bool); when(bool.getBoolean()).thenReturn(new Boolean(false)); when(hideInNav.getNodeData("hideInNav")).thenReturn(bool); when(bool.getBoolean()).thenReturn(new Boolean(true)); when(current.getNodeData("hideInNav")).thenReturn(bool); when(bool.getBoolean()).thenReturn(new Boolean(false)); when(dummy.getNodeData("navTitle")).thenReturn(string); when(string.getString("")).thenReturn("dummyTitle"); when(current.getHandle()).thenReturn("/"); when(dummy.getHandle()).thenReturn("/dummy"); when(dummy.getLevel()).thenReturn(1); when(current.getAncestors()).thenReturn(Arrays.asList(new Content[] {})); when(dummy.getNodeData("openMenu")).thenReturn(bool); when(bool.getBoolean()).thenReturn(false); when(dummy.getChildren()).thenReturn(new ArrayList<Content>()); when(dummy.getLevel()).thenReturn(1); when(current.getLevel()).thenReturn(0); when(dummy.getNodeData("accessKey")).thenReturn(string); when(string.getString("")).thenReturn(""); when(dummy.getHandle()).thenReturn("/dummy"); when(current.getNodeData("navTitle")).thenReturn(string); when(string.getString("")).thenReturn("currentTitle"); when(current.getHandle()).thenReturn("/"); when(current.getHandle()).thenReturn("/current"); when(current.getLevel()).thenReturn(1); when(current.getAncestors()).thenReturn(Arrays.asList(new Content[] {})); when(current.getNodeData("openMenu")).thenReturn(bool); when(bool.getBoolean()).thenReturn(false); when(current.getChildren()).thenReturn(new ArrayList<Content>()); when(current.getLevel()).thenReturn(1); when(current.getLevel()).thenReturn(0); when(current.getNodeData("accessKey")).thenReturn(string); when(string.getString("")).thenReturn(""); when(current.getHandle()).thenReturn("/current"); tag.doEndTag(); }
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); }
@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); }
EditorLinkTransformer implements LinkTransformer { @Override public String transform(Link uuidLink) { return new AbsolutePathTransformer(true,true,false).transform(uuidLink); } @Override String transform(Link uuidLink); }
@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); }
LinkUtil { public static String convertAbsoluteLinksToUUIDs(String html) { Matcher matcher = LINK_OR_IMAGE_PATTERN.matcher(html); StringBuffer res = new StringBuffer(); while (matcher.find()) { final String href = matcher.group(4); if (!isExternalLinkOrAnchor(href)) { try { Link link = parseLink(href); String linkStr = toPattern(link); linkStr = StringUtils.replace(linkStr, "\\", "\\\\"); linkStr = StringUtils.replace(linkStr, "$", "\\$"); matcher.appendReplacement(res, "$1" + linkStr + "$5"); } catch (LinkException e) { matcher.appendReplacement(res, "$0"); log.debug("can't parse link", e); } } else{ matcher.appendReplacement(res, "$0"); } } matcher.appendTail(res); return res.toString(); } static String convertUUIDtoHandle(String uuid, String workspaceName); static String convertUUIDtoURI(String uuid, String workspaceName); static String convertAbsoluteLinksToUUIDs(String html); static String convertLinksFromUUIDPattern(String str, LinkTransformer transformer); static String convertLinksFromUUIDPattern(String str); static boolean isInternalRelativeLink(String href); static boolean isExternalLinkOrAnchor(String href); static String makePathRelative(String url, String absolutePath); static String mapPathToRepository(String path); static void addParameter(StringBuffer uri, String name, String value); static String createAbsoluteLink(NodeData nodedata); static String createAbsoluteLink(Property property); static String createAbsoluteLink(String workspaceName, String uuid); static String createAbsoluteLink(Content content); static String createAbsoluteLink(Node node); static String createExternalLink(Content content); static String createExternalLink(Node node); static String createLink(Content node); static String createLink(Node node); static String createLink(NodeData nodedata); static String createLink(Property property); static String createLink(String workspaceName, String uuid); static Link createLinkInstance(Content node); static Link createLinkInstance(NodeData nodeData); static Link createLinkInstance(Property property); static Link createLinkInstance(String workspaceName, String uuid); static Link createLinkInstance(String workspaceName, String path, String extension, String anchor, String parameters); static Link createLinkInstance(String uuid, String workspaceName, String fallbackHandle, String nodeDataName, String extension, String anchor, String parameters); static Link parseUUIDLink(String uuidLink); static Link parseLink(String link); static String toPattern(Link link); static final Pattern EXTERNAL_LINK_PATTERN; static final String DEFAULT_EXTENSION; static final String DEFAULT_REPOSITORY; static final Pattern LINK_OR_IMAGE_PATTERN; static Pattern UUID_PATTERN; static final Pattern LINK_PATTERN; }
@Test public void testParsingLinks() { String res = LinkUtil.convertAbsoluteLinksToUUIDs(HTML_WITH_ABSOLUTE_LINK); assertEquals(HTML_WITH_UUIDS, res); } @Test public void testParsingLinksWithBackslashInQueryParam() { String res = LinkUtil.convertAbsoluteLinksToUUIDs("look <a href=\"/parent/sub.html?p4if_p=\\File%20Box\\Quick%20Reference%20Guides\\Strategy%20Management\\WIT\">here</a> for results"); assertEquals("look <a href=\"${link:{uuid:{2},repository:{website},path:{/parent/sub},nodeData:{},extension:{html}}}?p4if_p=\\File%20Box\\Quick%20Reference%20Guides\\Strategy%20Management\\WIT\">here</a> for results", res); }
LinkUtil { public static String convertLinksFromUUIDPattern(String str, LinkTransformer transformer) throws LinkException { Matcher matcher = UUID_PATTERN.matcher(str); StringBuffer res = new StringBuffer(); while (matcher.find()) { Link link = createLinkInstance(matcher.group(1), matcher.group(2), matcher.group(5), matcher.group(7), matcher.group(8), matcher.group(10), matcher.group(12)); String replacement = transformer.transform(link); replacement = StringUtils.replace(replacement, "\\", "\\\\"); replacement = StringUtils.replace(replacement,"$", "\\$"); matcher.appendReplacement(res, replacement); } matcher.appendTail(res); return res.toString(); } static String convertUUIDtoHandle(String uuid, String workspaceName); static String convertUUIDtoURI(String uuid, String workspaceName); static String convertAbsoluteLinksToUUIDs(String html); static String convertLinksFromUUIDPattern(String str, LinkTransformer transformer); static String convertLinksFromUUIDPattern(String str); static boolean isInternalRelativeLink(String href); static boolean isExternalLinkOrAnchor(String href); static String makePathRelative(String url, String absolutePath); static String mapPathToRepository(String path); static void addParameter(StringBuffer uri, String name, String value); static String createAbsoluteLink(NodeData nodedata); static String createAbsoluteLink(Property property); static String createAbsoluteLink(String workspaceName, String uuid); static String createAbsoluteLink(Content content); static String createAbsoluteLink(Node node); static String createExternalLink(Content content); static String createExternalLink(Node node); static String createLink(Content node); static String createLink(Node node); static String createLink(NodeData nodedata); static String createLink(Property property); static String createLink(String workspaceName, String uuid); static Link createLinkInstance(Content node); static Link createLinkInstance(NodeData nodeData); static Link createLinkInstance(Property property); static Link createLinkInstance(String workspaceName, String uuid); static Link createLinkInstance(String workspaceName, String path, String extension, String anchor, String parameters); static Link createLinkInstance(String uuid, String workspaceName, String fallbackHandle, String nodeDataName, String extension, String anchor, String parameters); static Link parseUUIDLink(String uuidLink); static Link parseLink(String link); static String toPattern(Link link); static final Pattern EXTERNAL_LINK_PATTERN; static final String DEFAULT_EXTENSION; static final String DEFAULT_REPOSITORY; static final Pattern LINK_OR_IMAGE_PATTERN; static Pattern UUID_PATTERN; static final Pattern LINK_PATTERN; }
@Test public void testUUIDToAbsoluteLinks() throws LinkException { String res = LinkUtil.convertLinksFromUUIDPattern(HTML_WITH_UUIDS, LinkTransformerManager.getInstance().getAbsolute(false)); assertEquals(HTML_WITH_ABSOLUTE_LINK, res); } @Test public void testUUIDToInternalLinks() throws LinkException { String res = LinkUtil.convertLinksFromUUIDPattern(HTML_WITH_UUIDS, LinkTransformerManager.getInstance().getEditorLink()); assertEquals(HTML_WITH_ABSOLUTE_LINK_AND_CONTEXT_PATH, res); } @Test public void testUUIDToRootLinks() throws LinkException { String res = LinkUtil.convertLinksFromUUIDPattern("<p>Large article pages have a <a href=\"${link:{uuid:{2a98b29f-b514-4949-9cb3-e1162171a2ca},repository:{website},handle:{/features/special-templates},nodeData:{},extension:{html}}}\">Table Of Contents</a> (<a href=\"${link:{uuid:{},repository:{website},handle:{/},nodeData:{},extension:{html}}}\">TOC</a>) navigation.</p>", LinkTransformerManager.getInstance().getEditorLink()); assertEquals("<p>Large article pages have a <a href=\"/some-context/features/special-templates.html\">Table Of Contents</a> (<a href=\"/some-context/\">TOC</a>) navigation.</p>", res); } @Test public void testUUIDToRelativeLinks() throws LinkException { String res = LinkUtil.convertLinksFromUUIDPattern(HTML_WITH_UUIDS, LinkTransformerManager.getInstance().getRelative("/parent/sub2")); assertEquals(StringUtils.replace(HTML_WITH_ABSOLUTE_LINK, "/parent/sub.html", "sub.html"), res); } @Test public void testUUIDToAbsoluteLinkWithDollar() throws LinkException { String htmlAbsoluteWithDollar = "this is a <a href=\"" + HREF_ABSOLUTE_LINK + "?var=${some_var}\">test</a>"; String htmlUuidWithDollar = "this is a <a href=\"" + UUID_PATTERN_SIMPLE + "?var=${some_var}\">test</a>"; String res = LinkUtil.convertLinksFromUUIDPattern(htmlUuidWithDollar, LinkTransformerManager.getInstance().getAbsolute(false)); assertEquals(htmlAbsoluteWithDollar, res); } @Test public void testCreateUndefinedLinkIfUUIDIsNonExistentOrFallbackHandleIsEmpty() { try { String link = LinkUtil.convertLinksFromUUIDPattern("<p>Large article pages have a <a href=\"${link:{uuid:{00060890-0220-4544-b6a4-320325dcfd86},repository:{website},handle:{},nodeData:{},extension:{html}}}\">Table Of Contents</a></p>", LinkTransformerManager.getInstance().getEditorLink()); assertEquals("<p>Large article pages have a <a href=\"/some-context/\">Table Of Contents</a></p>", link); } catch (LinkException e) { fail("Got unexpected exception "+ e.getMessage()); } }
LinkUtil { public static Link parseLink(String link) throws LinkException{ link = StringUtils.removeStart(link, MgnlContext.getContextPath()); Matcher matcher = LINK_PATTERN.matcher(link); if(matcher.matches()){ String orgHandle = matcher.group(1); orgHandle = Components.getComponent(I18nContentSupport.class).toRawURI(orgHandle); String workspaceName = getURI2RepositoryManager().getRepository(orgHandle); String handle = getURI2RepositoryManager().getHandle(orgHandle); return createLinkInstance(workspaceName, handle, matcher.group(3),matcher.group(5),matcher.group(7)); } throw new LinkException("can't parse [ " + link + "]"); } static String convertUUIDtoHandle(String uuid, String workspaceName); static String convertUUIDtoURI(String uuid, String workspaceName); static String convertAbsoluteLinksToUUIDs(String html); static String convertLinksFromUUIDPattern(String str, LinkTransformer transformer); static String convertLinksFromUUIDPattern(String str); static boolean isInternalRelativeLink(String href); static boolean isExternalLinkOrAnchor(String href); static String makePathRelative(String url, String absolutePath); static String mapPathToRepository(String path); static void addParameter(StringBuffer uri, String name, String value); static String createAbsoluteLink(NodeData nodedata); static String createAbsoluteLink(Property property); static String createAbsoluteLink(String workspaceName, String uuid); static String createAbsoluteLink(Content content); static String createAbsoluteLink(Node node); static String createExternalLink(Content content); static String createExternalLink(Node node); static String createLink(Content node); static String createLink(Node node); static String createLink(NodeData nodedata); static String createLink(Property property); static String createLink(String workspaceName, String uuid); static Link createLinkInstance(Content node); static Link createLinkInstance(NodeData nodeData); static Link createLinkInstance(Property property); static Link createLinkInstance(String workspaceName, String uuid); static Link createLinkInstance(String workspaceName, String path, String extension, String anchor, String parameters); static Link createLinkInstance(String uuid, String workspaceName, String fallbackHandle, String nodeDataName, String extension, String anchor, String parameters); static Link parseUUIDLink(String uuidLink); static Link parseLink(String link); static String toPattern(Link link); static final Pattern EXTERNAL_LINK_PATTERN; static final String DEFAULT_EXTENSION; static final String DEFAULT_REPOSITORY; static final Pattern LINK_OR_IMAGE_PATTERN; static Pattern UUID_PATTERN; static final Pattern LINK_PATTERN; }
@Test public void testMakeUUIDFromAbsolutePath() throws LinkException{ String uuid = LinkUtil.parseLink("/parent/sub").getUUID(); assertEquals("2", uuid); }
LinkUtil { public static String makePathRelative(String url, String absolutePath){ String fromPath = StringUtils.substringBeforeLast(url, "/"); String toPath = StringUtils.substringBeforeLast(absolutePath, "/"); if (StringUtils.equals(fromPath, toPath) && StringUtils.endsWith(absolutePath, "/")) { return "."; } String[] fromDirectories = StringUtils.split(fromPath, "/"); String[] toDirectories = StringUtils.split(toPath, "/"); int pos=0; while(pos < fromDirectories.length && pos < toDirectories.length && fromDirectories[pos].equals(toDirectories[pos])){ pos++; } StringBuilder rel = new StringBuilder(); for(int i=pos; i < fromDirectories.length; i++ ){ rel.append("../"); } for(int i=pos; i < toDirectories.length; i++ ){ rel.append(toDirectories[i] + "/"); } rel.append(StringUtils.substringAfterLast(absolutePath, "/")); return rel.toString(); } static String convertUUIDtoHandle(String uuid, String workspaceName); static String convertUUIDtoURI(String uuid, String workspaceName); static String convertAbsoluteLinksToUUIDs(String html); static String convertLinksFromUUIDPattern(String str, LinkTransformer transformer); static String convertLinksFromUUIDPattern(String str); static boolean isInternalRelativeLink(String href); static boolean isExternalLinkOrAnchor(String href); static String makePathRelative(String url, String absolutePath); static String mapPathToRepository(String path); static void addParameter(StringBuffer uri, String name, String value); static String createAbsoluteLink(NodeData nodedata); static String createAbsoluteLink(Property property); static String createAbsoluteLink(String workspaceName, String uuid); static String createAbsoluteLink(Content content); static String createAbsoluteLink(Node node); static String createExternalLink(Content content); static String createExternalLink(Node node); static String createLink(Content node); static String createLink(Node node); static String createLink(NodeData nodedata); static String createLink(Property property); static String createLink(String workspaceName, String uuid); static Link createLinkInstance(Content node); static Link createLinkInstance(NodeData nodeData); static Link createLinkInstance(Property property); static Link createLinkInstance(String workspaceName, String uuid); static Link createLinkInstance(String workspaceName, String path, String extension, String anchor, String parameters); static Link createLinkInstance(String uuid, String workspaceName, String fallbackHandle, String nodeDataName, String extension, String anchor, String parameters); static Link parseUUIDLink(String uuidLink); static Link parseLink(String link); static String toPattern(Link link); static final Pattern EXTERNAL_LINK_PATTERN; static final String DEFAULT_EXTENSION; static final String DEFAULT_REPOSITORY; static final Pattern LINK_OR_IMAGE_PATTERN; static Pattern UUID_PATTERN; static final Pattern LINK_PATTERN; }
@Test public void testMakingRelativeLinks() { assertEquals("d.html", LinkUtil.makePathRelative("/a/b/c.html", "/a/b/d.html")); assertEquals("c/e.html", LinkUtil.makePathRelative("/a/b/c.html", "/a/b/c/e.html")); assertEquals("../x/y.html", LinkUtil.makePathRelative("/a/b/c.html", "/a/x/y.html")); assertEquals("../../z/x/y.html", LinkUtil.makePathRelative("/a/b/c.html", "/z/x/y.html")); assertEquals("../../../b.html", LinkUtil.makePathRelative("/a/b/c/d/e.html", "/a/b.html")); assertEquals("a/b.html", LinkUtil.makePathRelative("/a.html", "/a/b.html")); assertEquals(".", LinkUtil.makePathRelative("/a.html", "/")); assertEquals(".", LinkUtil.makePathRelative("/b/a.html", "/b/")); assertEquals("../", LinkUtil.makePathRelative("/c/b/a.html", "/c/")); }
LinkUtil { public static boolean isInternalRelativeLink(String href) { return !isExternalLinkOrAnchor(href) && !href.startsWith("/"); } static String convertUUIDtoHandle(String uuid, String workspaceName); static String convertUUIDtoURI(String uuid, String workspaceName); static String convertAbsoluteLinksToUUIDs(String html); static String convertLinksFromUUIDPattern(String str, LinkTransformer transformer); static String convertLinksFromUUIDPattern(String str); static boolean isInternalRelativeLink(String href); static boolean isExternalLinkOrAnchor(String href); static String makePathRelative(String url, String absolutePath); static String mapPathToRepository(String path); static void addParameter(StringBuffer uri, String name, String value); static String createAbsoluteLink(NodeData nodedata); static String createAbsoluteLink(Property property); static String createAbsoluteLink(String workspaceName, String uuid); static String createAbsoluteLink(Content content); static String createAbsoluteLink(Node node); static String createExternalLink(Content content); static String createExternalLink(Node node); static String createLink(Content node); static String createLink(Node node); static String createLink(NodeData nodedata); static String createLink(Property property); static String createLink(String workspaceName, String uuid); static Link createLinkInstance(Content node); static Link createLinkInstance(NodeData nodeData); static Link createLinkInstance(Property property); static Link createLinkInstance(String workspaceName, String uuid); static Link createLinkInstance(String workspaceName, String path, String extension, String anchor, String parameters); static Link createLinkInstance(String uuid, String workspaceName, String fallbackHandle, String nodeDataName, String extension, String anchor, String parameters); static Link parseUUIDLink(String uuidLink); static Link parseLink(String link); static String toPattern(Link link); static final Pattern EXTERNAL_LINK_PATTERN; static final String DEFAULT_EXTENSION; static final String DEFAULT_REPOSITORY; static final Pattern LINK_OR_IMAGE_PATTERN; static Pattern UUID_PATTERN; static final Pattern LINK_PATTERN; }
@Test public void testInternalRelativeLinksAreProperlyDetermined() { assertTrue(LinkUtil.isInternalRelativeLink("foo")); assertTrue(LinkUtil.isInternalRelativeLink("foo/bar")); assertTrue(LinkUtil.isInternalRelativeLink("foo/bar.gif")); assertFalse(LinkUtil.isInternalRelativeLink("/foo")); assertFalse(LinkUtil.isInternalRelativeLink("/foo/bar")); assertFalse(LinkUtil.isInternalRelativeLink("/foo/bar.gif")); assertFalse(LinkUtil.isInternalRelativeLink("http: assertFalse(LinkUtil.isInternalRelativeLink("http: assertFalse(LinkUtil.isInternalRelativeLink("http: assertFalse(LinkUtil.isInternalRelativeLink("http: assertFalse(LinkUtil.isInternalRelativeLink("http: assertFalse(LinkUtil.isInternalRelativeLink("http: assertFalse(LinkUtil.isInternalRelativeLink("https: assertFalse(LinkUtil.isInternalRelativeLink("https: assertFalse(LinkUtil.isInternalRelativeLink("ftp: assertFalse(LinkUtil.isInternalRelativeLink("mailto:[email protected]")); assertFalse(LinkUtil.isInternalRelativeLink("tel:12345")); assertFalse(LinkUtil.isInternalRelativeLink("tel:+41 0800 80 80")); assertFalse(LinkUtil.isInternalRelativeLink("#anchor")); assertFalse(LinkUtil.isInternalRelativeLink("#another-anchor")); assertFalse(LinkUtil.isInternalRelativeLink("javascript:void(window.open('http: assertFalse(LinkUtil.isInternalRelativeLink("javascript:void(window.open('/foo/bar','','resizable=no,location=no,menubar=no,scrollbars=no,status=no,toolbar=no,fullscreen=no,dependent=no,width=200,height=200'))")); }
LinkUtil { public static boolean isExternalLinkOrAnchor(String href) { return LinkUtil.EXTERNAL_LINK_PATTERN.matcher(href).matches() || href.startsWith("#"); } static String convertUUIDtoHandle(String uuid, String workspaceName); static String convertUUIDtoURI(String uuid, String workspaceName); static String convertAbsoluteLinksToUUIDs(String html); static String convertLinksFromUUIDPattern(String str, LinkTransformer transformer); static String convertLinksFromUUIDPattern(String str); static boolean isInternalRelativeLink(String href); static boolean isExternalLinkOrAnchor(String href); static String makePathRelative(String url, String absolutePath); static String mapPathToRepository(String path); static void addParameter(StringBuffer uri, String name, String value); static String createAbsoluteLink(NodeData nodedata); static String createAbsoluteLink(Property property); static String createAbsoluteLink(String workspaceName, String uuid); static String createAbsoluteLink(Content content); static String createAbsoluteLink(Node node); static String createExternalLink(Content content); static String createExternalLink(Node node); static String createLink(Content node); static String createLink(Node node); static String createLink(NodeData nodedata); static String createLink(Property property); static String createLink(String workspaceName, String uuid); static Link createLinkInstance(Content node); static Link createLinkInstance(NodeData nodeData); static Link createLinkInstance(Property property); static Link createLinkInstance(String workspaceName, String uuid); static Link createLinkInstance(String workspaceName, String path, String extension, String anchor, String parameters); static Link createLinkInstance(String uuid, String workspaceName, String fallbackHandle, String nodeDataName, String extension, String anchor, String parameters); static Link parseUUIDLink(String uuidLink); static Link parseLink(String link); static String toPattern(Link link); static final Pattern EXTERNAL_LINK_PATTERN; static final String DEFAULT_EXTENSION; static final String DEFAULT_REPOSITORY; static final Pattern LINK_OR_IMAGE_PATTERN; static Pattern UUID_PATTERN; static final Pattern LINK_PATTERN; }
@Test public void testExternalLinksAreProperlyDetermined() { assertFalse(LinkUtil.isExternalLinkOrAnchor("foo")); assertFalse(LinkUtil.isExternalLinkOrAnchor("foo/bar")); assertFalse(LinkUtil.isExternalLinkOrAnchor("foo/bar.gif")); assertFalse(LinkUtil.isExternalLinkOrAnchor("/foo")); assertFalse(LinkUtil.isExternalLinkOrAnchor("/foo/bar")); assertFalse(LinkUtil.isExternalLinkOrAnchor("/foo/bar.gif")); assertTrue(LinkUtil.isExternalLinkOrAnchor("http: assertTrue(LinkUtil.isExternalLinkOrAnchor("http: assertTrue(LinkUtil.isExternalLinkOrAnchor("http: assertTrue(LinkUtil.isExternalLinkOrAnchor("http: assertTrue(LinkUtil.isExternalLinkOrAnchor("http: assertTrue(LinkUtil.isExternalLinkOrAnchor("http: assertTrue(LinkUtil.isExternalLinkOrAnchor("https: assertTrue(LinkUtil.isExternalLinkOrAnchor("https: assertTrue(LinkUtil.isExternalLinkOrAnchor("ftp: assertTrue(LinkUtil.isExternalLinkOrAnchor("mailto:[email protected]")); assertTrue(LinkUtil.isExternalLinkOrAnchor("tel:12345")); assertTrue(LinkUtil.isExternalLinkOrAnchor("tel:+41 0800 80 80")); assertTrue(LinkUtil.isExternalLinkOrAnchor("#anchor")); assertTrue(LinkUtil.isExternalLinkOrAnchor("#another-anchor")); assertTrue(LinkUtil.isExternalLinkOrAnchor("javascript:void(window.open('http: assertTrue(LinkUtil.isExternalLinkOrAnchor("javascript:void(window.open('/foo/bar','','resizable=no,location=no,menubar=no,scrollbars=no,status=no,toolbar=no,fullscreen=no,dependent=no,width=200,height=200'))")); }
LinkUtil { public static Link createLinkInstance(Content node) { return createLinkInstance(node.getJCRNode()); } static String convertUUIDtoHandle(String uuid, String workspaceName); static String convertUUIDtoURI(String uuid, String workspaceName); static String convertAbsoluteLinksToUUIDs(String html); static String convertLinksFromUUIDPattern(String str, LinkTransformer transformer); static String convertLinksFromUUIDPattern(String str); static boolean isInternalRelativeLink(String href); static boolean isExternalLinkOrAnchor(String href); static String makePathRelative(String url, String absolutePath); static String mapPathToRepository(String path); static void addParameter(StringBuffer uri, String name, String value); static String createAbsoluteLink(NodeData nodedata); static String createAbsoluteLink(Property property); static String createAbsoluteLink(String workspaceName, String uuid); static String createAbsoluteLink(Content content); static String createAbsoluteLink(Node node); static String createExternalLink(Content content); static String createExternalLink(Node node); static String createLink(Content node); static String createLink(Node node); static String createLink(NodeData nodedata); static String createLink(Property property); static String createLink(String workspaceName, String uuid); static Link createLinkInstance(Content node); static Link createLinkInstance(NodeData nodeData); static Link createLinkInstance(Property property); static Link createLinkInstance(String workspaceName, String uuid); static Link createLinkInstance(String workspaceName, String path, String extension, String anchor, String parameters); static Link createLinkInstance(String uuid, String workspaceName, String fallbackHandle, String nodeDataName, String extension, String anchor, String parameters); static Link parseUUIDLink(String uuidLink); static Link parseLink(String link); static String toPattern(Link link); static final Pattern EXTERNAL_LINK_PATTERN; static final String DEFAULT_EXTENSION; static final String DEFAULT_REPOSITORY; static final Pattern LINK_OR_IMAGE_PATTERN; static Pattern UUID_PATTERN; static final Pattern LINK_PATTERN; }
@Test public void testMakeAbsolutePathFromUUID() throws LinkException { String absolutePath = LinkUtil.createLinkInstance(RepositoryConstants.WEBSITE, "2").getPath(); assertEquals("/parent/sub", absolutePath); } @Test public void testMakeCompleteURL() throws Exception { ServerConfiguration serverConfiguration = Components.getComponent(ServerConfiguration.class); String base = serverConfiguration.getDefaultBaseUrl(); serverConfiguration.setDefaultBaseUrl("http: String url = null; try { MockSession session = new MockSession("website"); MockNode c = (MockNode) session.getRootNode(); url = LinkTransformerManager.getInstance().getCompleteUrl().transform(LinkUtil.createLinkInstance(c)); } finally { serverConfiguration.setDefaultBaseUrl(base); } assertNotNull(url); assertEquals(-1, StringUtils.substringAfter(url, "http: }
ComponentProviderConfigurationBuilder { protected ComponentConfiguration getComponent(ComponentDefinition definition) { if (isProvider(definition)) { return getProvider(definition); } else if (isImplementation(definition)) { return getImplementation(definition); } else if (isConfigured(definition)) { return getConfigured(definition); } else if (isObserved(definition)) { return getObserved(definition); } else { throw new ComponentConfigurationException("Unable to add component with key " + definition.getType()); } } ComponentProviderConfiguration readConfiguration(List<String> resourcePaths, String id); ComponentProviderConfiguration getComponentsFromModules(String id, List<ModuleDefinition> moduleDefinitions); void addComponents(ComponentProviderConfiguration configuration, ComponentsDefinition componentsDefinition); }
@Test public void testNonScopedComponent() { GuiceComponentProvider componentProvider = getComponentProvider("test-components-simple.xml"); assertNoMoreEvents(); SimpleComponent simpleComponent = componentProvider.getComponent(SimpleComponent.class); assertEvent("SimpleComponent"); assertNoMoreEvents(); SimpleComponent simpleComponent2 = componentProvider.getComponent(SimpleComponent.class); assertEvent("SimpleComponent"); assertNoMoreEvents(); assertNotSame(simpleComponent, simpleComponent2); componentProvider.destroy(); assertNoMoreEvents(); } @Test public void testLazySingletonScopedComponent() { GuiceComponentProvider componentProvider = getComponentProvider("test-components-simple-singleton.xml"); assertNoMoreEvents(); SimpleComponent simpleComponent = componentProvider.getComponent(SimpleComponent.class); assertEvent("SimpleComponent"); assertNoMoreEvents(); SimpleComponent simpleComponent2 = componentProvider.getComponent(SimpleComponent.class); assertNoMoreEvents(); assertSame(simpleComponent, simpleComponent2); componentProvider.destroy(); assertNoMoreEvents(); } @Test public void testEagerSingletonScopedComponent() { GuiceComponentProvider componentProvider = getComponentProvider("test-components-simple-eagersingleton.xml"); assertEvent("SimpleComponent"); assertNoMoreEvents(); SimpleComponent simpleComponent = componentProvider.getComponent(SimpleComponent.class); assertNoMoreEvents(); SimpleComponent simpleComponent2 = componentProvider.getComponent(SimpleComponent.class); assertNoMoreEvents(); assertSame(simpleComponent, simpleComponent2); componentProvider.destroy(); assertNoMoreEvents(); } @Test public void testProvider() { GuiceComponentProvider componentProvider = getComponentProvider("test-components-provider.xml"); assertNoMoreEvents(); SimpleComponent simpleComponent = componentProvider.getComponent(SimpleComponent.class); assertEvent("SimpleComponent"); assertNoMoreEvents(); SimpleComponent simpleComponent2 = componentProvider.getComponent(SimpleComponent.class); assertEvent("SimpleComponent"); assertNoMoreEvents(); assertNotSame(simpleComponent, simpleComponent2); componentProvider.destroy(); assertNoMoreEvents(); } @Test public void testSingletonScopedProvider() { GuiceComponentProvider componentProvider = getComponentProvider("test-components-provider-singleton.xml"); assertNoMoreEvents(); SimpleComponent simpleComponent = componentProvider.getComponent(SimpleComponent.class); assertEvent("SimpleComponent"); assertNoMoreEvents(); SimpleComponent simpleComponent2 = componentProvider.getComponent(SimpleComponent.class); assertNoMoreEvents(); assertSame(simpleComponent, simpleComponent2); componentProvider.destroy(); assertNoMoreEvents(); } @Test public void testComponentFactory() { GuiceComponentProvider componentProvider = getComponentProvider("test-components-componentfactory.xml"); assertNoMoreEvents(); SimpleComponent simpleComponent = componentProvider.getComponent(SimpleComponent.class); assertEvent("SimpleComponent"); assertNoMoreEvents(); SimpleComponent simpleComponent2 = componentProvider.getComponent(SimpleComponent.class); assertEvent("SimpleComponent"); assertNoMoreEvents(); assertNotSame(simpleComponent, simpleComponent2); componentProvider.destroy(); assertNoMoreEvents(); } @Test public void testSingletonScopedComponentFactory() { GuiceComponentProvider componentProvider = getComponentProvider("test-components-componentfactory-singleton.xml"); assertNoMoreEvents(); SimpleComponent simpleComponent = componentProvider.getComponent(SimpleComponent.class); assertEvent("SimpleComponent"); assertNoMoreEvents(); SimpleComponent simpleComponent2 = componentProvider.getComponent(SimpleComponent.class); assertNoMoreEvents(); assertSame(simpleComponent, simpleComponent2); componentProvider.destroy(); assertNoMoreEvents(); } @Test public void testConfigured() { GuiceComponentProvider componentProvider = getComponentProvider("test-components-configured.xml"); assertNoMoreEvents(); SimpleComponent simpleComponent = componentProvider.getComponent(SimpleComponent.class); assertEvent("SimpleComponent"); assertNoMoreEvents(); SimpleComponent simpleComponent2 = componentProvider.getComponent(SimpleComponent.class); assertEvent("SimpleComponent"); assertNoMoreEvents(); assertNotSame(simpleComponent, simpleComponent2); componentProvider.destroy(); assertNoMoreEvents(); } @Test public void testConfiguredSingleton() { GuiceComponentProvider componentProvider = getComponentProvider("test-components-configured-singleton.xml"); assertNoMoreEvents(); SimpleComponent simpleComponent = componentProvider.getComponent(SimpleComponent.class); assertEvent("SimpleComponent"); assertNoMoreEvents(); SimpleComponent simpleComponent2 = componentProvider.getComponent(SimpleComponent.class); assertNoMoreEvents(); assertSame(simpleComponent, simpleComponent2); componentProvider.destroy(); assertNoMoreEvents(); } @Test public void testConfiguredEagerSingleton() { GuiceComponentProvider componentProvider = getComponentProvider("test-components-configured-eagersingleton.xml"); assertEvent("SimpleComponent"); assertNoMoreEvents(); SimpleComponent simpleComponent = componentProvider.getComponent(SimpleComponent.class); assertNoMoreEvents(); SimpleComponent simpleComponent2 = componentProvider.getComponent(SimpleComponent.class); assertNoMoreEvents(); assertSame(simpleComponent, simpleComponent2); componentProvider.destroy(); assertNoMoreEvents(); } @Test public void testObserved() { GuiceComponentProvider componentProvider = getComponentProvider("test-components-observed.xml"); assertNoMoreEvents(); SimpleComponentWithProperty simpleComponent = componentProvider.getComponent(SimpleComponentWithProperty.class); assertEvent("SimpleComponent"); assertEvent("SimpleComponent"); assertNoMoreEvents(); SimpleComponentWithProperty simpleComponent2 = componentProvider.getComponent(SimpleComponentWithProperty.class); assertEvent("SimpleComponent"); assertEvent("SimpleComponent"); assertNoMoreEvents(); simpleComponent.setName("1"); simpleComponent2.setName("2"); assertEquals("1", simpleComponent.getName()); assertEquals("2", simpleComponent2.getName()); componentProvider.destroy(); assertNoMoreEvents(); }
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); }
@Test public void testCanReadPlatformComponentsFile() { ComponentConfigurationReader reader = new ComponentConfigurationReader(); ComponentsDefinition componentsDefinition = reader.readFromResource(MagnoliaServletContextListener.DEFAULT_PLATFORM_COMPONENTS_CONFIG_LOCATION); assertTrue(componentsDefinition.getComponents().size() > 0); }
DefaultClassFactory implements ClassFactory { @Override public <T> T newInstance(final Class<T> c, final Class<?>[] argTypes, final Object... params) { if (argTypes.length != params.length) { throw new IllegalStateException("Argument types and values do not match! " + Arrays.asList(argTypes) + " / " + Arrays.asList(params)); } return newInstance(c, params, new Invoker<T>() { @Override public T invoke() throws InvocationTargetException, NoSuchMethodException, IllegalAccessException, InstantiationException { return (T) ConstructorUtils.invokeConstructor(c, params, argTypes); } }); } @Override Class<C> forName(String className); @Override T newInstance(final Class<T> c, final Class<?>[] argTypes, final Object... params); @Override T newInstance(final Class<T> c, final Object... params); }
@Test public void testCanInstantiateWithEmptyConstructor() { final DefaultClassFactory classFactory = new DefaultClassFactory(); assertEquals("default", classFactory.newInstance(FooBar.class).getValue()); assertEquals("default", classFactory.newInstance(FooBar.class, new String[0]).getValue()); assertEquals("default", classFactory.newInstance(FooBar.class, null).getValue()); } @Test public void testCanInstantiateWithAppropriateConstructor() { final DefaultClassFactory classFactory = new DefaultClassFactory(); assertEquals("bingo", classFactory.newInstance(FooBar.class, "bingo").getValue()); assertEquals("bingo123", classFactory.newInstance(FooBar.class, "bingo", Long.valueOf(123)).getValue()); } @Test public void testCanInstantiateWithAppropriateConstructorAndNullParamsWhenSignatureIsSpecified() { final DefaultClassFactory classFactory = new DefaultClassFactory(); assertEquals("bingo", classFactory.newInstance(FooBar.class, arr(String.class), "bingo").getValue()); assertEquals("bingo123", classFactory.newInstance(FooBar.class, arr(String.class, Object.class), "bingo", Long.valueOf(123)).getValue()); assertEquals("bingonull", classFactory.newInstance(FooBar.class, arr(String.class, Object.class), "bingo", null).getValue()); assertEquals("null7", classFactory.newInstance(FooBar.class, arr(String.class, Object.class), null, Long.valueOf(7)).getValue()); } @Test public void testCanInstantiateWithBestMatchingConstructorWhenTheSignatureIsMorePrecise() { final DefaultClassFactory classFactory = new DefaultClassFactory(); try { assertEquals("bingo7", classFactory.newInstance(FooBar.class, arr(String.class, Long.class), "bingo", Long.valueOf(7)).getValue()); } catch (MgnlInstantiationException e) { fail("It should have used the more generic constructor <init>(String, Object)"); } try { assertEquals("bingo", classFactory.newInstance(FooBar.class, arr(Object.class), "bingo").getValue()); fail("should have failed"); } catch (MgnlInstantiationException e) { } } @Test public void testCanInstantiateWithSingleArgConstructorAndNullParamWhenSignatureIspecified() { final DefaultClassFactory classFactory = new DefaultClassFactory(); assertEquals(null, classFactory.newInstance(FooBar.class, arr(String.class), new Object[]{null}).getValue()); assertEquals(null, classFactory.newInstance(FooBar.class, arr(String.class), new String[]{null}).getValue()); }
GuiceComponentProvider implements ComponentProvider { @Override public <T> T getComponent(Class<T> type) throws NoSuchComponentException{ if (!GuiceUtils.hasExplicitBindingFor(injector, type)) { throw new NoSuchComponentException("No component configuration for type [" + type.getName() + "] found. Please add a configuration to your module descriptor."); } return injector.getInstance(type); } GuiceComponentProvider(Map<Class<?>, Class<?>> typeMappings, GuiceComponentProvider parentComponentProvider); @Override Class<? extends T> getImplementation(Class<T> type); @Override @Deprecated T getSingleton(Class<T> type); @Override T getComponent(Class<T> type); @Override T newInstance(Class<T> type, Object... parameters); @Override T newInstanceWithParameterResolvers(Class<T> type, ParameterResolver... parameterResolvers); Injector getInjector(); Provider<T> getProvider(Class<T> type); void injectMembers(Object instance); void destroy(); @Override GuiceComponentProvider getParent(); }
@Test public void testGetComponentProvider() { ComponentProviderConfiguration configuration = new ComponentProviderConfiguration(); GuiceComponentProvider p = createComponentProvider(configuration); assertSame(p, p.getComponent(ComponentProvider.class)); } @Test (expected=NoSuchComponentException.class) public void getComponentThrowsExeptionForUnconfiguredType() { ComponentProviderConfiguration configuration = new ComponentProviderConfiguration(); GuiceComponentProvider p = createComponentProvider(configuration); p.getComponent(StringBuilder.class); } @Test public void testInstance() { ComponentProviderConfiguration configuration = new ComponentProviderConfiguration(); SingletonObject singletonObject = new SingletonObject(); configuration.registerInstance(SingletonObject.class, singletonObject); GuiceComponentProvider p = createComponentProvider(configuration); assertSame(singletonObject, p.getComponent(SingletonObject.class)); assertSame(singletonObject, p.getComponent(SingletonObject.class)); } @Test public void testImplementation() { ComponentProviderConfiguration configuration = new ComponentProviderConfiguration(); configuration.registerImplementation(SingletonObject.class, SingletonObject.class); GuiceComponentProvider p = createComponentProvider(configuration); SingletonObject singletonObject = p.getComponent(SingletonObject.class); assertNotNull(singletonObject); assertSame(singletonObject, p.getComponent(SingletonObject.class)); } @Test public void testConfigured() { ComponentProviderConfiguration configuration = new ComponentProviderConfiguration(); configuration.addComponent(new ConfiguredComponentConfiguration<SingletonObject>(SingletonObject.class, "/foo/bar/singleton")); GuiceComponentProvider p = createComponentProviderWithContent2Bean(configuration, true); SingletonObject singletonObject = p.getComponent(SingletonObject.class); assertNotNull(singletonObject); assertNotSame(singletonObject, p.getComponent(SingletonObject.class)); assertEquals("foobar", p.getComponent(SingletonObject.class).getName()); } @Test public void testConfiguredInSingletonScope() { ComponentProviderConfiguration configuration = new ComponentProviderConfiguration(); ConfiguredComponentConfiguration<SingletonObject> componentConfiguration = new ConfiguredComponentConfiguration<SingletonObject>(SingletonObject.class, "/foo/bar/singleton"); componentConfiguration.setScope(ComponentDefinition.SCOPE_SINGLETON); configuration.addComponent(componentConfiguration); GuiceComponentProvider p = createComponentProviderWithContent2Bean(configuration, true); SingletonObject singletonObject = p.getComponent(SingletonObject.class); assertNotNull(singletonObject); assertSame(singletonObject, p.getComponent(SingletonObject.class)); assertEquals("foobar", p.getComponent(SingletonObject.class).getName()); } @Test public void testObserved() { ComponentProviderConfiguration configuration = new ComponentProviderConfiguration(); ConfiguredComponentConfiguration<SingletonObject> observed = new ConfiguredComponentConfiguration<SingletonObject>(SingletonObject.class, RepositoryConstants.CONFIG, "/foo/bar/singleton", true); observed.setScope(ComponentDefinition.SCOPE_SINGLETON); configuration.addComponent(observed); GuiceComponentProvider p = createComponentProviderWithContent2Bean(configuration, true); SingletonObject singletonObject = p.getComponent(SingletonObject.class); assertNotNull(singletonObject); assertSame(singletonObject, p.getComponent(SingletonObject.class)); assertEquals("foobar", p.getComponent(SingletonObject.class).getName()); } @Test public void testObservedInRequestScope() { ComponentProviderConfiguration configuration = new ComponentProviderConfiguration(); ConfiguredComponentConfiguration<SingletonObject> observed = new ConfiguredComponentConfiguration<SingletonObject>(SingletonObject.class, RepositoryConstants.CONFIG, "/foo/bar/singleton", true); observed.setScope(ComponentDefinition.SCOPE_LOCAL); configuration.addComponent(observed); MockHttpServletRequest request = new MockHttpServletRequest(); ((MockWebContext) MgnlContext.getWebContext()).setRequest(request); GuiceComponentProvider p = createComponentProviderWithContent2Bean(configuration, true); SingletonObject singletonObject = p.getComponent(SingletonObject.class); assertNotNull(singletonObject); assertSame(singletonObject, p.getComponent(SingletonObject.class)); assertEquals("foobar", p.getComponent(SingletonObject.class).getName()); request.clearAttributes(); SingletonObject singletonObject2 = p.getComponent(SingletonObject.class); assertNotNull(singletonObject2); assertNotSame(singletonObject2, singletonObject); assertSame(singletonObject2, p.getComponent(SingletonObject.class)); assertEquals("foobar", p.getComponent(SingletonObject.class).getName()); } @Test public void testCreateChild() { ComponentProviderConfiguration configuration = new ComponentProviderConfiguration(); configuration.registerImplementation(SingletonObject.class, SingletonObject.class); GuiceComponentProvider parent = createComponentProvider(configuration); ComponentProviderConfiguration childConfig = new ComponentProviderConfiguration(); childConfig.registerImplementation(OtherSingletonObject.class, OtherSingletonObject.class); GuiceComponentProvider child = createChild(parent, childConfig); assertNotSame(parent, child); assertNotNull(parent.getComponent(SingletonObject.class)); assertNotNull(child.getComponent(SingletonObject.class)); assertSame(parent.getComponent(SingletonObject.class), child.getComponent(SingletonObject.class)); try{ parent.getComponent(OtherSingletonObject.class); fail("the parent should not know " + OtherSingletonObject.class); } catch(NoSuchComponentException e){ } assertNotNull(child.getComponent(OtherSingletonObject.class)); } @Test public void canAccessProperties() throws IOException { Properties properties = new Properties(); properties.setProperty("alpha", "AAA"); properties.setProperty("beta", "true"); TestMagnoliaConfigurationProperties configurationProperties = new TestMagnoliaConfigurationProperties(properties); ComponentProviderConfiguration parentConfiguration = new ComponentProviderConfiguration(); parentConfiguration.registerInstance(MagnoliaConfigurationProperties.class, configurationProperties); GuiceComponentProvider parent = new GuiceComponentProviderBuilder().withConfiguration(parentConfiguration).build(); ComponentProviderConfiguration childConfiguration = new ComponentProviderConfiguration(); childConfiguration.registerImplementation(SingletonWithPropertyDependencies.class); GuiceComponentProvider child = new GuiceComponentProviderBuilder().withConfiguration(childConfiguration).withParent(parent).build(); SingletonWithPropertyDependencies component = child.getComponent(SingletonWithPropertyDependencies.class); assertEquals("AAA", component.getAlpha()); assertTrue(component.getBeta()); }
ObjectManufacturer { public Object newInstance(Class<?> clazz, ParameterResolver... parameterResolvers) { Constructor<?>[] constructors = clazz.getDeclaredConstructors(); Constructor<?> selectedConstructor = null; for (Constructor<?> constructor : constructors) { if (constructor.isAnnotationPresent(Inject.class)) { if (selectedConstructor != null) { throw new MgnlInstantiationException("Only one constructor can use @Inject [" + clazz + "]"); } selectedConstructor = constructor; } } if (selectedConstructor != null) { selectedConstructor.setAccessible(true); Object[] parameters = resolveParameters(selectedConstructor, parameterResolvers); if (parameters == null) { throw new MgnlInstantiationException("Unable to resolve parameters for constructor " + selectedConstructor); } return newInstance(selectedConstructor, parameters); } int bestScore = -1; Object[] bestParameters = null; for (Constructor<?> constructor : constructors) { if (!Modifier.isPublic(constructor.getModifiers())) { continue; } int score = constructor.getParameterTypes().length; if (score < bestScore) { continue; } Object[] parameters = resolveParameters(constructor, parameterResolvers); if (parameters == null) { continue; } selectedConstructor = constructor; bestScore = score; bestParameters = parameters; } if (selectedConstructor != null) { return newInstance(selectedConstructor, bestParameters); } throw new MgnlInstantiationException("No suitable constructor found for class [" + clazz + "]"); } Object newInstance(Class<?> clazz, ParameterResolver... parameterResolvers); }
@Test public void testParameterFromGuice() { NameableObject object = (NameableObject) manufacturer.newInstance( ObjectWithAnnotatedConstructor.class, new GuiceParameterResolver(injector)); assertEquals("foobar", object.getName()); } @Test public void testCandidateTakesPrecedence() { NameableObject object2 = (NameableObject) manufacturer.newInstance( ObjectWithAnnotatedConstructor.class, new CandidateParameterResolver(new Object[]{"12345"}), new GuiceParameterResolver(injector)); assertEquals("12345", object2.getName()); } @Test(expected = MgnlInstantiationException.class) public void testFailsWhenNoParameterCanBeResolved() { manufacturer.newInstance( ObjectWithAnnotatedConstructor.class, new CandidateParameterResolver(new Object[]{})); } @Test public void testParameterFromGuiceWithGreedyConstructor() { NameableObject object = (NameableObject) manufacturer.newInstance( ObjectWithGreedyConstructor.class, new GuiceParameterResolver(injector)); assertEquals("foobar", object.getName()); } @Test public void testCandidateTakesPrecedenceWithGreedyConstructor() { NameableObject object2 = (NameableObject) manufacturer.newInstance( ObjectWithGreedyConstructor.class, new CandidateParameterResolver(new Object[]{"12345"}), new GuiceParameterResolver(injector)); assertEquals("12345", object2.getName()); } @Test public void testIgnoresPrivateConstructor() { NameableObject object = (NameableObject) manufacturer.newInstance( ObjectWithGreediestConstructorPrivate.class, new GuiceParameterResolver(injector)); assertNull(object.getName()); } @Test(expected = MgnlInstantiationException.class) public void testFailesOnMultipleAnnotatedConstructors() { manufacturer.newInstance(ObjectWithMultipleAnnotatedConstructors.class); } @Test(expected = MgnlInstantiationException.class) public void testFailWhenConstructorThrowsException() { manufacturer.newInstance( ObjectWithConstructorThatThrowsException.class, new GuiceParameterResolver(injector)); } @Test(expected = MgnlInstantiationException.class) public void testFfailsWhenNoPublicConstructorAvailable() { manufacturer.newInstance( ObjectWithNoPrivateConstructor.class, new GuiceParameterResolver(injector)); } @Test public void testCanGetProviderFromCandidate() { NameableObject object = (NameableObject) manufacturer.newInstance( ObjectWithProviderParameter.class, new CandidateParameterResolver(new Object[]{"12345"})); assertEquals("12345", object.getName()); } @Test public void testCanGetProviderFromGuice() { NameableObject object = (NameableObject) manufacturer.newInstance( ObjectWithProviderParameter.class, new GuiceParameterResolver(injector)); assertEquals("foobar", object.getName()); }
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(); }
@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()); }
DefaultComponentProvider implements ComponentProvider { @Override @Deprecated public synchronized <T> T getSingleton(Class<T> type) { return getComponent(type); } DefaultComponentProvider(final MagnoliaConfigurationProperties mappings); DefaultComponentProvider(Properties mappings); @Override @Deprecated synchronized T getSingleton(Class<T> type); @Override synchronized T getComponent(Class<T> type); @Override T newInstance(Class<T> type, Object... parameters); @Override T newInstanceWithParameterResolvers(Class<T> type, ParameterResolver... parameters); @Override Class<? extends C> getImplementation(Class<C> type); @Override ComponentProvider getParent(); void setImplementation(Class<?> type, String impl); void setInstance(Class<?> type, Object instance); void setInstanceFactory(Class<?> type, ComponentFactory<?> factory); void clear(); }
@Test public void testReturnsGivenConcreteClassIfNoneConfigured() { final DefaultComponentProvider componentProvider = new DefaultComponentProvider(new Properties()); Object obj = componentProvider.getSingleton(TestImplementation.class); assertTrue(obj instanceof TestImplementation); } @Test public void testBlowsIfGivenInterfaceAndNoImplementationIsConfigured() { final DefaultComponentProvider componentProvider = new DefaultComponentProvider(new Properties()); try { componentProvider.getSingleton(TestInterface.class); fail("should have thrown a MgnlInstantiationException"); } catch (MgnlInstantiationException e) { assertEquals("No concrete implementation defined for interface info.magnolia.objectfactory.DefaultComponentProviderTest$TestInterface", e.getMessage()); } } @Test public void testReturnsConfiguredImplementation() { final Properties p = new Properties(); p.setProperty("info.magnolia.objectfactory.DefaultComponentProviderTest$TestInterface", "info.magnolia.objectfactory.DefaultComponentProviderTest$TestImplementation"); final DefaultComponentProvider componentProvider = new DefaultComponentProvider(p); Object obj = componentProvider.getSingleton(TestInterface.class); assertTrue(obj instanceof TestImplementation); } @Test public void testGetSingletonReturnsSameInstance() { final ComponentProvider cp = new DefaultComponentProvider(new Properties()); assertEquals(cp.getSingleton(TestImplementation.class), cp.getSingleton(TestImplementation.class)); assertSame(cp.getSingleton(TestImplementation.class), cp.getSingleton(TestImplementation.class)); } @Test public void testUsesComponentFactoryIfSuchFactoryIsConfigured() { final Properties p = new Properties(); p.setProperty("info.magnolia.objectfactory.DefaultComponentProviderTest$TestInterface", "info.magnolia.objectfactory.DefaultComponentProviderTest$TestInstanceFactory"); final DefaultComponentProvider componentProvider = new DefaultComponentProvider(p); final TestInterface obj = componentProvider.getSingleton(TestInterface.class); assertTrue(obj instanceof TestOtherImplementation); assertSame(obj, componentProvider.getSingleton(TestInterface.class)); } @Test public void testSingletonDefinedInRepositoryDefaultToConfigWorkspace() throws RepositoryException, IOException { setDefaultImplementationsAndInitMockRepository("/test", RepositoryConstants.CONFIG, "test.class=" + TestImplementation.class.getName() ); Object obj = Components.getSingleton(TestInterface.class); assertNotNull(obj); assertTrue(obj instanceof TestImplementation); } @Test public void testSingletonDefinedInRepositoryUsesGivenRepoName() throws RepositoryException, IOException { setDefaultImplementationsAndInitMockRepository("dummy:/test", "dummy", "test.class=" + TestImplementation.class.getName() ); Object obj = Components.getSingleton(TestInterface.class); assertNotNull(obj); assertTrue(obj instanceof TestImplementation); } @Test public void testProxiesReturnedByObserverComponentFactoryCanBeCastToTheirSubclass() throws Exception { setDefaultImplementationsAndInitMockRepository("config:/test", "config", "test.class=" + TestOtherImplementation.class.getName() ); TestInterface obj = Components.getSingleton(TestInterface.class); assertNotNull(obj); assertTrue(obj instanceof TestOtherImplementation); assertEquals("bar", ((TestOtherImplementation) obj).getFoo()); }
DefaultComponentProvider implements ComponentProvider { @Override public <T> T newInstance(Class<T> type, Object... parameters) { if (type == null) { log.error("type can't be null", new Throwable()); return null; } try { if (factories.containsKey(type)) { final ComponentFactory<T> factory = (ComponentFactory<T>) factories.get(type); return factory.newInstance(); } final String className = getImplementationName(type); if (isInRepositoryDefinition(className)) { final ComponentConfigurationPath path = new ComponentConfigurationPath(className); final ObservedComponentFactory<T> factory = new ObservedComponentFactory<T>(path.getRepository(), path.getPath(), type, this); setInstanceFactory(type, factory); return newInstance(type); } final Class<?> clazz = Classes.getClassFactory().forName(className); if (!Classes.isConcrete(clazz)) { throw new MgnlInstantiationException("No concrete implementation defined for " + clazz); } final Object instance = Classes.getClassFactory().newInstance(clazz, parameters); if (instance instanceof ComponentFactory) { final ComponentFactory<T> factory = (ComponentFactory<T>) instance; setInstanceFactory(type, factory); return factory.newInstance(); } return (T) instance; } catch (Exception e) { if (e instanceof MgnlInstantiationException) { throw (MgnlInstantiationException) e; } throw new MgnlInstantiationException("Can't instantiate an implementation of this class [" + type.getName() + "]: " + ExceptionUtils.getMessage(e), e); } } DefaultComponentProvider(final MagnoliaConfigurationProperties mappings); DefaultComponentProvider(Properties mappings); @Override @Deprecated synchronized T getSingleton(Class<T> type); @Override synchronized T getComponent(Class<T> type); @Override T newInstance(Class<T> type, Object... parameters); @Override T newInstanceWithParameterResolvers(Class<T> type, ParameterResolver... parameters); @Override Class<? extends C> getImplementation(Class<C> type); @Override ComponentProvider getParent(); void setImplementation(Class<?> type, String impl); void setInstance(Class<?> type, Object instance); void setInstanceFactory(Class<?> type, ComponentFactory<?> factory); void clear(); }
@Test public void testNewInstanceReallyReturnsNewInstance() { final ComponentProvider cp = new DefaultComponentProvider(new Properties()); assertNotSame(cp.newInstance(TestImplementation.class), cp.newInstance(TestImplementation.class)); }
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(); }
@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()); }
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(); }
@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()); }
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(); }
@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")); }
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; }
@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")); }
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); }
@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)); }
TemplatingFunctions { public ContentMap parent(ContentMap contentMap) throws RepositoryException { return contentMap == null ? null : asContentMap(this.parent(contentMap.getJCRNode())); } @Inject TemplatingFunctions(Provider<AggregationState> aggregationStateProvider); Node asJCRNode(ContentMap contentMap); ContentMap asContentMap(Node content); List<Node> children(Node content); List<Node> children(Node content, String nodeTypeName); List<ContentMap> children(ContentMap content); List<ContentMap> children(ContentMap content, String nodeTypeName); ContentMap root(ContentMap contentMap); ContentMap root(ContentMap contentMap, String nodeTypeName); Node root(Node content); Node root(Node content, String nodeTypeName); ContentMap parent(ContentMap contentMap); ContentMap parent(ContentMap contentMap, String nodeTypeName); Node parent(Node content); Node parent(Node content, String nodeTypeName); ContentMap page(ContentMap content); Node page(Node content); List<ContentMap> ancestors(ContentMap contentMap); List<ContentMap> ancestors(ContentMap contentMap, String nodeTypeName); List<Node> ancestors(Node content); List<Node> ancestors(Node content, String nodeTypeName); Node inherit(Node content); Node inherit(Node content, String relPath); ContentMap inherit(ContentMap content); ContentMap inherit(ContentMap content, String relPath); Property inheritProperty(Node content, String relPath); Property inheritProperty(ContentMap content, String relPath); List<Node> inheritList(Node content, String relPath); List<ContentMap> inheritList(ContentMap content, String relPath); boolean isInherited(Node content); boolean isInherited(ContentMap content); boolean isFromCurrentPage(Node content); boolean isFromCurrentPage(ContentMap content); String link(String workspace, String nodeIdentifier); @Deprecated String link(Property property); String link(Node content); String link(ContentMap contentMap); String language(); String externalLink(Node content, String linkPropertyName); String externalLink(ContentMap content, String linkPropertyName); String externalLinkTitle(Node content, String linkPropertyName, String linkTitlePropertyName); String externalLinkTitle(ContentMap content, String linkPropertyName, String linkTitlePropertyName); boolean isEditMode(); boolean isPreviewMode(); boolean isAuthorInstance(); boolean isPublicInstance(); String createHtmlAttribute(String name, String value); SiblingsHelper siblings(Node node); SiblingsHelper siblings(ContentMap node); Node content(String path); Node content(String repository, String path); Node contentByIdentifier(String id); Node contentByIdentifier(String repository, String id); List<ContentMap> asContentMapList(Collection<Node> nodeList); List<Node> asNodeList(Collection<ContentMap> contentMapList); ContentMap decode(ContentMap content); Node decode(Node content); Node encode(Node content); String metaData(Node content, String property); String metaData(ContentMap content, String property); Collection<Node> search(String workspace, String statement, String language, String returnItemType); Collection<Node> simpleSearch(String workspace, String statement, String returnItemType, String startPath); }
@Test public void testParentFromRootNodeShouldBeNull() throws RepositoryException { Node resultNode = functions.parent(root); assertNull(resultNode); } @Test public void testParentFromNodeDepth1() throws RepositoryException { Node resultNode = functions.parent(topPage); assertNodeEqualsNode(root, resultNode); } @Test public void testParentFromNodeDepth2() throws RepositoryException { Node resultNode = functions.parent(childPage); assertNodeEqualsNode(topPage, resultNode); } @Test public void testParentFromRootContentMapShouldBeNull() throws RepositoryException { Node resultNode = functions.parent(root); assertNull(resultNode); } @Test public void testParentFromContentMapDepth1() throws RepositoryException { ContentMap resultContentMap = functions.parent(topPageContentMap); assertMapEqualsMap(rootContentMap, resultContentMap); } @Test public void testParentFromContentMapDepth2() throws RepositoryException { ContentMap resultContentMap = functions.parent(childPageContentMap); assertMapEqualsMap(topPageContentMap, resultContentMap); } @Test public void testParentPageFromPageNode() throws RepositoryException { Node resultNode = functions.parent(childPage, NodeTypes.Page.NAME); assertNodeEqualsNode(topPage, resultNode); } @Test public void testParentComponentFromPageNode() throws RepositoryException { Node resultNode = functions.parent(childPage, NodeTypes.Component.NAME); assertNull(resultNode); } @Test public void testParentPageFromNodeDepth1() throws RepositoryException { Node resultNode = functions.parent(topPage, NodeTypes.Page.NAME); assertNull(resultNode); } @Test public void testParentPageFromComponentNodeDepth1() throws RepositoryException { Node resultNode = functions.parent(topPageComponent, NodeTypes.Page.NAME); assertEquals(topPage, resultNode); } @Test public void testParentPageFromComponentNodeDepth2() throws RepositoryException { Node resultNode = functions.parent(childPageComponent, NodeTypes.Page.NAME); assertEquals(childPage, resultNode); } @Test public void testParentPageFromComponentNodeDepth3() throws RepositoryException { Node childPageSubSubComponent = childPageComponent.addNode("subSubComponent", NodeTypes.Component.NAME); Node resultNode = functions.parent(childPageSubSubComponent, NodeTypes.Page.NAME); assertNodeEqualsNode(childPage, resultNode); } @Test public void testParentPageFromPageContentMap() throws RepositoryException { ContentMap resultContentMap = functions.parent(childPageContentMap, NodeTypes.Page.NAME); assertMapEqualsMap(topPageContentMap, resultContentMap); } @Test public void testParentComponentFromPageContentMap() throws RepositoryException { ContentMap resultNode = functions.parent(childPageContentMap, NodeTypes.Component.NAME); assertNull(resultNode); } @Test public void testParentPageFromContentMapDepth1() throws RepositoryException { ContentMap resultNode = functions.parent(topPageContentMap, NodeTypes.Page.NAME); assertNull(resultNode); } @Test public void testParentPageFromComponentContentMapDepth1() throws RepositoryException { ContentMap resultContentMap = functions.parent(topPageComponentContentMap, NodeTypes.Page.NAME); assertMapEqualsMap(topPageContentMap, resultContentMap); } @Test public void testParentPageFromComponentContentMapDepth2() throws RepositoryException { ContentMap resultContentMap = functions.parent(childPageComponentContentMap, NodeTypes.Page.NAME); assertMapEqualsMap(childPageContentMap, resultContentMap); } @Test public void testParentPageFromComponentContentMapDepth3() throws RepositoryException { ContentMap childPageSubSubComponentContentMap = new ContentMap(childPageComponent.addNode("subSubComponent", NodeTypes.Component.NAME)); ContentMap resultContentMap = functions.parent(childPageSubSubComponentContentMap, NodeTypes.Page.NAME); assertMapEqualsMap(childPageContentMap, resultContentMap); }
PropertiesImportExport { protected Object convertPropertyStringToObject(String valueStr) { if (contains(valueStr, ':')) { final String type = StringUtils.substringBefore(valueStr, ":"); final String value = StringUtils.substringAfter(valueStr, ":"); if (type.equalsIgnoreCase("date")) { return ISO8601.parse(value); } else if (type.equalsIgnoreCase("binary")) { return new ByteArrayInputStream(value.getBytes()); } else { try { final Class<?> typeCl; if (type.equals("int")) { typeCl = Integer.class; } else { typeCl = Class.forName("java.lang." + StringUtils.capitalize(type)); } return ConvertUtils.convert(value, typeCl); } catch (ClassNotFoundException e) { return valueStr; } } } return valueStr; } void createNodes(Node root, String... properties); void createNodes(Node root, InputStream propertiesStream); Properties toProperties(Node node, final AbstractPredicate<Node> nodePredicate); }
@Test public void testConvertsToWrapperType() { assertEquals(Boolean.TRUE, pie.convertPropertyStringToObject("boolean:true")); assertEquals(Boolean.FALSE, pie.convertPropertyStringToObject("boolean:false")); assertEquals(Integer.valueOf(5), pie.convertPropertyStringToObject("integer:5")); final Object dateConvertedObject = pie.convertPropertyStringToObject("date:2009-10-14T08:59:01.227-04:00"); assertTrue(dateConvertedObject instanceof Calendar); assertEquals(1255525141227L, ((Calendar) dateConvertedObject).getTimeInMillis()); final Object dateOnlyObject = pie.convertPropertyStringToObject("date:2009-12-12"); assertNull(dateOnlyObject); } @Test public void testConvertPropertyStringToBinaryObject() throws Exception { Object result = pie.convertPropertyStringToObject("binary:R0lGODlhUABrAPcAAGYAAOi2lOi9ne2thO2le+Wdc+y3kvGWZe2zjOfDpu+fc+iuivCabOajfOjBouerhOfGqeeabfCWaOixjuange+idu+pf2wJB2gCAumhdH0fGHMSDuSgeYwzKOCzlnEPC7d0YNaliuWWbHYWEZ1IOeuviYQpIKRLN+ungMuVfapiUZI4KsaLc6VaSt6LYrdjSZVAM3kZE4svJNyOaN2vkp5RRJtMP9WFYNaKZYEjG6VTQWoFBOGlgnobFcdzUr1yWMd5W7dxXOG3m+mpf4ksIqxYQpxDMtipjtijhsCBarhgRZE7MNOfheSPZOGTa+W4moElHcOEbI45L8+bg5I1J96rjMV8Ybt9aMyOc7x3YG8NCsFxVLNdRK9oVcBpS9OCXYw2LeaRZbxlSbx7Zs53Vc6Qdb9sT9CCYNKZfJpFNqdfTpRCNtJ/W6xeScl4VqFINbJmUcdvUIcuJOCbdc1+XLl4ZMaIb7VsV8mTfMOHcKpRO5hGOaZeT+SwkLBqV4YvJ6pfTAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAAIEALAAAAABQAGsAAAj/AAMIHEiw4EADBgQiXJhQIcOHECNKnDjRoMWDFDNq3MjRAAIEFwM0xPiQYMeTCz9q/MgSpMiRIU3CLIiSocqWLT3i3Nky5kWVAlkuDCBUJ8+jSJMijelSqdOnUJMOGPBx6oAJWLNq3ar16ISoSUtMZWm1rNmzVheoXbtgAtu3akvI1RqXKgK0ePPq3ZsWrt+/cPkKHiwYsOG/DwgrXlyW7YPHkCNLlsy4Ml8LmDNbUDu5s+fIAxLr1YzZKunTqE8TWM2awOfXkIcMaUCBwgMLU2XjHlC6NevMvoMLH+47cm3bxyk0WM68+fLWzxuwlk68uvXrBJLXpq3c+XPs4MML/69Avrz58sm9O19NXTxr8qvLE6gQX/788+cV6N/Pf7/6/9K1V0EGBGZA32oKxFdAASI4MQMOOMwwwxlbmHEGDiLoh19/HHbYH4DqEUhfgSRWwJ8INwDhhRJ6nEACCSecsEQPG3SQRhE+uODhjjzqB2IGBZAoZIELFlmAEze8sAIUG3ywAwBQRiklBhqcQEcEPfbHwJZcdslAASEaGSSQYhapH4M3iLHCBhhI6eabUMrggwhedqlfnXhuuRyYZZbJ45E+rPABnIS+KYMXTeSp6JYSeMlcn34q0GcEM7ygQZuFZhqlBkok2mWjdYJ6wAGNjjoqpKgqEMGqrEbgwgs5YP+qqaZUikGqBKbmquuupqJaZqvAiuBDB7LOSisRcUigLK68NturrwsCK60bK1xg7LUAfHCCC6TyyqyzB0AbrbSrMvAFCRtgey2VSigLLrjQktuqCyewqe61F1BBxrvwQrpqAfJGIIKl96r7wRvc8ssrqgGz+kW1BWN7gQz7Lmvxt80y3LAI9UasbgxcXOwuv+ICHOwPRFjrMb4d3HCrws+WPC4OEK+MrQZbjAxzuDIXGcEPGtis7ghc8KszqT0b+cIIQmOrrai7MourxUkXScKgTRt7gRFhcJkrA8uOavEBzXFQAAcNmA3pDTKonLWmW3fttbKMiqysc2gvx0Hee/f assertTrue(result instanceof InputStream); ((InputStream) result).close(); } @Test public void testCanUseIntShortcutForConvertingIntegers() { assertEquals(Integer.valueOf(37), pie.convertPropertyStringToObject("int:37")); }
PropertiesImportExport { public void createNodes(Node root, String... properties) throws IOException, RepositoryException { createNodes(root, IOUtils.toInputStream(StringUtils.join(Arrays.asList(properties), "\n"))); } void createNodes(Node root, String... properties); void createNodes(Node root, InputStream propertiesStream); Properties toProperties(Node node, final AbstractPredicate<Node> nodePredicate); }
@Test public void testCreateNodes() throws Exception { final MockNode root = new MockNode(); String content = "/parent1/sub1.prop1=one\n" + "/parent2/sub2\n" + "/parent2/sub2.prop1=two"; pie.createNodes(root, new ByteArrayInputStream(content.getBytes())); assertEquals("one", root.getNode("/parent1/sub1").getProperty("prop1").getString()); assertTrue(root.hasNode("/parent2/sub2")); assertEquals("two", root.getNode("/parent2/sub2").getProperty("prop1").getString()); content = "/parent1/sub1.@uuid=1\n" + "/parent2/sub2.@uuid=2"; pie.createNodes(root, new ByteArrayInputStream(content.getBytes())); assertEquals("1", root.getNode("/parent1/sub1").getIdentifier()); assertEquals("2", root.getNode("/parent2/sub2").getIdentifier()); } @Test(expected = IllegalArgumentException.class) public void testCreateNodesFailingBecauseOfEqualsSignWithoutADot() throws Exception { final MockNode root = new MockNode(); String content = "/parent/sub/prop=2"; pie.createNodes(root, new ByteArrayInputStream(content.getBytes())); } @Test(expected = IllegalArgumentException.class) public void testCreateNodesFailingBecauseOfMissingTrailingSlash() throws Exception { String content = "parent/sub@uuid=1"; pie.createNodes(null, new ByteArrayInputStream(content.getBytes())); } @Test(expected = Exception.class) public void testCreateNodesFailingBecauseOfDotAndMonkeyTail() throws Exception { String content = "/parent/sub@uuid=1"; pie.createNodes(null, new ByteArrayInputStream(content.getBytes())); } @Test(expected = Exception.class) public void testCreateNodesFailingBecauseOfDotInPath() throws Exception { String content = "/parent.sub.@uuid=1"; pie.createNodes(null, new ByteArrayInputStream(content.getBytes())); }
PropertiesImportExport { public Properties toProperties(Node node, final AbstractPredicate<Node> nodePredicate) throws RepositoryException { final Properties out = new OrderedProperties(); NodeUtil.visit( node, new NodeVisitor() { @Override public void visit(Node node) throws RepositoryException { appendNodeTypeAndIdentifier(node, out); appendNodeProperties(node, out); } }, nodePredicate ); return out; } void createNodes(Node root, String... properties); void createNodes(Node root, InputStream propertiesStream); Properties toProperties(Node node, final AbstractPredicate<Node> nodePredicate); }
@Test public void testDoesntExportRootNode() throws RepositoryException { Properties p = pie.toProperties(new MockNode(), new AbstractPredicate<Node>() { @Override public boolean evaluateTyped(Node node) { return true; } }); assertTrue(p.isEmpty()); } @Test public void testExportsProperties() throws RepositoryException { MockNode node = new MockNode("nodename"); node.setProperty("string-property", "string-value"); node.setProperty("int-property", 42); node.setProperty("long-property", 12); Calendar date = Calendar.getInstance(); node.setProperty("date-property", date); node.setProperty("double-property", 1.2345d); node.setProperty("boolean-property", true); node.setProperty("path-property", "/some/path", PropertyType.PATH); node.setProperty("binary-property", new BinaryValue("test string to be used as binary data its contents does not matter")); Properties p = pie.toProperties(node, new AbstractPredicate<Node>() { @Override public boolean evaluateTyped(Node node) { return true; } }); assertFalse(p.isEmpty()); assertContains(p, "/nodename.@type", node.getPrimaryNodeType().getName()); assertContains(p, "/nodename.@uuid", node.getIdentifier()); assertContains(p, "/nodename.string-property", "string-value"); assertContains(p, "/nodename.int-property", "42"); assertContains(p, "/nodename.long-property", "12"); assertContains(p, "/nodename.date-property", "date:" + ISO8601.format(date)); assertContains(p, "/nodename.double-property", "1.2345"); assertContains(p, "/nodename.boolean-property", "boolean:true"); assertContains(p, "/nodename.path-property", "/some/path"); assertContains(p, "/nodename.binary-property", "binary:test string to be used as binary data its contents does not matter"); }
TemplatingFunctions { public List<Node> children(Node content) throws RepositoryException { return content == null ? null : asNodeList(NodeUtil.getNodes(content, NodeUtil.EXCLUDE_META_DATA_FILTER)); } @Inject TemplatingFunctions(Provider<AggregationState> aggregationStateProvider); Node asJCRNode(ContentMap contentMap); ContentMap asContentMap(Node content); List<Node> children(Node content); List<Node> children(Node content, String nodeTypeName); List<ContentMap> children(ContentMap content); List<ContentMap> children(ContentMap content, String nodeTypeName); ContentMap root(ContentMap contentMap); ContentMap root(ContentMap contentMap, String nodeTypeName); Node root(Node content); Node root(Node content, String nodeTypeName); ContentMap parent(ContentMap contentMap); ContentMap parent(ContentMap contentMap, String nodeTypeName); Node parent(Node content); Node parent(Node content, String nodeTypeName); ContentMap page(ContentMap content); Node page(Node content); List<ContentMap> ancestors(ContentMap contentMap); List<ContentMap> ancestors(ContentMap contentMap, String nodeTypeName); List<Node> ancestors(Node content); List<Node> ancestors(Node content, String nodeTypeName); Node inherit(Node content); Node inherit(Node content, String relPath); ContentMap inherit(ContentMap content); ContentMap inherit(ContentMap content, String relPath); Property inheritProperty(Node content, String relPath); Property inheritProperty(ContentMap content, String relPath); List<Node> inheritList(Node content, String relPath); List<ContentMap> inheritList(ContentMap content, String relPath); boolean isInherited(Node content); boolean isInherited(ContentMap content); boolean isFromCurrentPage(Node content); boolean isFromCurrentPage(ContentMap content); String link(String workspace, String nodeIdentifier); @Deprecated String link(Property property); String link(Node content); String link(ContentMap contentMap); String language(); String externalLink(Node content, String linkPropertyName); String externalLink(ContentMap content, String linkPropertyName); String externalLinkTitle(Node content, String linkPropertyName, String linkTitlePropertyName); String externalLinkTitle(ContentMap content, String linkPropertyName, String linkTitlePropertyName); boolean isEditMode(); boolean isPreviewMode(); boolean isAuthorInstance(); boolean isPublicInstance(); String createHtmlAttribute(String name, String value); SiblingsHelper siblings(Node node); SiblingsHelper siblings(ContentMap node); Node content(String path); Node content(String repository, String path); Node contentByIdentifier(String id); Node contentByIdentifier(String repository, String id); List<ContentMap> asContentMapList(Collection<Node> nodeList); List<Node> asNodeList(Collection<ContentMap> contentMapList); ContentMap decode(ContentMap content); Node decode(Node content); Node encode(Node content); String metaData(Node content, String property); String metaData(ContentMap content, String property); Collection<Node> search(String workspace, String statement, String language, String returnItemType); Collection<Node> simpleSearch(String workspace, String statement, String returnItemType, String startPath); }
@Test public void testChildrenFromNode() throws RepositoryException { String[] expectedNamesDepth1 = (String[]) ArrayUtils.addAll(DEPTH_2_COMPONENT_NAMES, DEPTH_2_PAGE_NAMES); List<Node> resultChildNodes = functions.children(topPage); assertNodesListEqualStringDefinitions(expectedNamesDepth1, resultChildNodes); } @Test public void testChildrenFromNodeAndTypePage() throws RepositoryException { List<Node> resultChildPages = functions.children(topPage, NodeTypes.Page.NAME); assertNodesListEqualStringDefinitions(DEPTH_2_PAGE_NAMES, resultChildPages); } @Test public void testChildrenFromNodeAndTypeComponent() throws RepositoryException { List<Node> resultChildComponents = functions.children(topPage, NodeTypes.Component.NAME); assertNodesListEqualStringDefinitions(DEPTH_2_COMPONENT_NAMES, resultChildComponents); } @Test public void testChildrenFromContentMap() throws RepositoryException { String[] expectedNamesDepth1 = (String[]) ArrayUtils.addAll(DEPTH_2_COMPONENT_NAMES, DEPTH_2_PAGE_NAMES); List<ContentMap> resultChildNodes = functions.children(topPageContentMap); assertContentMapListEqualStringDefinitions(expectedNamesDepth1, resultChildNodes); } @Test public void testChildrenFromContentMapAndTypePage() throws RepositoryException { List<ContentMap> resultChildPages = functions.children(topPageContentMap, NodeTypes.Page.NAME); assertContentMapListEqualStringDefinitions(DEPTH_2_PAGE_NAMES, resultChildPages); } @Test public void testChildrenFromContentMapAndTypeComponent() throws RepositoryException { List<ContentMap> resultChildComponents = functions.children(topPageContentMap, NodeTypes.Component.NAME); assertContentMapListEqualStringDefinitions(DEPTH_2_COMPONENT_NAMES, resultChildComponents); }
PropertyUtil { @SuppressWarnings("unchecked") public static void setProperty(Node node, String propertyName, Object propertyValue) throws RepositoryException { if (node == null) { throw new IllegalArgumentException("Cannot set a property on a null-node!"); } if (propertyName == null) { throw new IllegalArgumentException("Cannot set a property without a provided name"); } if (propertyValue == null){ node.setProperty(propertyName, (Value) null); } else if (propertyValue instanceof Value) { node.setProperty(propertyName, (Value) propertyValue); } else if (propertyValue instanceof Node) { node.setProperty(propertyName, (Node) propertyValue); } else if (propertyValue instanceof Binary) { node.setProperty(propertyName, (Binary) propertyValue); } else if (propertyValue instanceof Calendar) { node.setProperty(propertyName, (Calendar) propertyValue); } else if (propertyValue instanceof Date) { Calendar cal = Calendar.getInstance(); cal.setTime((Date) propertyValue); node.setProperty(propertyName, cal); } else if (propertyValue instanceof BigDecimal) { node.setProperty(propertyName, (BigDecimal) propertyValue); } else if (propertyValue instanceof String) { node.setProperty(propertyName, (String) propertyValue); } else if (propertyValue instanceof Long) { node.setProperty(propertyName, ((Long) propertyValue).longValue()); } else if (propertyValue instanceof Double) { node.setProperty(propertyName, (Double) propertyValue); } else if (propertyValue instanceof Boolean) { node.setProperty(propertyName, (Boolean) propertyValue); } else if (propertyValue instanceof InputStream) { node.setProperty(propertyName, (InputStream) propertyValue); } else if (propertyValue instanceof Collection) { String[] list = new String[((Collection<Object>)propertyValue).size()]; int pos = 0; for (Object value : (Collection<Object>)propertyValue) { list[pos] = value.toString(); pos +=1; } node.setProperty(propertyName, list); } else { throw new IllegalArgumentException("Cannot set property to a value of type " + propertyValue.getClass()); } } 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); }
@Test(expected = IllegalArgumentException.class) public void testSetPropertyThrowsExceptionOnNullNode() throws RepositoryException { PropertyUtil.setProperty(null, null, null); } @Test(expected = IllegalArgumentException.class) public void testSetPropertyThrowsExceptionOnNullName() throws RepositoryException { PropertyUtil.setProperty(root, null, null); } @Test public void testSetPropertyToNul() throws RepositoryException { final Object value = null; PropertyUtil.setProperty(root, PROPERTY_NAME, value); assertFalse(root.hasProperty(PROPERTY_NAME)); }
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); }
@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); }
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); }
@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()); }
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); }
@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); }
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); }
@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); }
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); }
@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); }
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); }
@Test public void testGetMetaData() throws Exception { MetaData md = MetaDataUtil.getMetaData(testNode); assertNotNull(md); }
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); }
@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()); }
ContentMap implements Map<String, Object> { @Override public Object get(Object key) { String keyStr; try { keyStr = (String) key; } catch (ClassCastException e) { throw new ClassCastException("ContentMap accepts only String as a parameters, provided object was of type " + (key == null ? "null" : key.getClass().getName())); } Object prop = getNodeProperty(keyStr); if (prop == null) { keyStr = convertDeprecatedProps(keyStr); return getSpecialProperty(keyStr); } return prop; } ContentMap(Node content); @Override boolean containsKey(Object key); @Override Object get(Object key); @Override int size(); @Override Set<String> keySet(); @Override Set<java.util.Map.Entry<String, Object>> entrySet(); @Override Collection<Object> values(); @Override boolean containsValue(Object arg0); @Override boolean isEmpty(); @Override void clear(); @Override Object put(String arg0, Object arg1); @Override void putAll(Map<? extends String, ? extends Object> arg0); @Override Object remove(Object arg0); Node getJCRNode(); }
@Test public void testGetBinaryProps() throws Exception { String contentProperties = StringUtils.join(Arrays.asList( "/somepage/mypage.@type=mgnl:content", "/somepage/mypage/paragraphs.@type=mgnl:contentNode", "/somepage/mypage/paragraphs/0.@type=mgnl:contentNode", "/somepage/mypage/paragraphs/0.@type=mgnl:contentNode", "/somepage/mypage/paragraphs/0/attachment1.@type=mgnl:resource", "/somepage/mypage/paragraphs/0/attachment1.fileName=hello", "/somepage/mypage/paragraphs/0/attachment1.extension=gif", "/somepage/mypage/paragraphs/0/attachment1.jcr\\:data=binary:X", "/somepage/mypage/paragraphs/0/attachment1.jcr\\:mimeType=image/gif", "/somepage/mypage/paragraphs/0/attachment1.jcr\\:lastModified=date:2009-10-14T08:59:01.227-04:00", "/somepage/mypage/paragraphs/0/attachment2.jcr\\:data=binary:X", "/somepage/mypage/paragraphs/0/attachment2.@type=mgnl:resource", "/somepage/mypage/paragraphs/0/attachment2.fileName=test", "/somepage/mypage/paragraphs/0/attachment2.extension=jpeg", "/somepage/mypage/paragraphs/0/attachment2.jcr\\:mimeType=image/jpeg", "/somepage/mypage/paragraphs/0/attachment2.jcr\\:lastModified=date:2009-10-14T08:59:01.227-04:00", "/somepage/mypage/paragraphs/0/image3.jcr\\:data=binary:X", "/somepage/mypage/paragraphs/0/image3.@type=mgnl:resource", "/somepage/mypage/paragraphs/0/image3.fileName=third", "/somepage/mypage/paragraphs/0/image3.extension=png", "/somepage/mypage/paragraphs/0/image3.jcr\\:mimeType=image/png", "/somepage/mypage/paragraphs/0/image3.jcr\\:lastModified=date:2009-10-14T08:59:01.227-04:00", "/somepage/mypage/paragraphs/0.foo=bar", "/somepage/mypage/paragraphs/0.mybool=boolean:true", "/somepage/mypage/paragraphs/0/rand.jcr\\:data=binary:X", "/somepage/mypage/paragraphs/0/rand.@type=mgnl:resource", "/somepage/mypage/paragraphs/0/rand.fileName=randdddd", "/somepage/mypage/paragraphs/0/rand.extension=png", "/somepage/mypage/paragraphs/0/rand.jcr\\:mimeType=image/png", "/somepage/mypage/paragraphs/0/rand.jcr\\:lastModified=date:2009-10-14T08:59:01.227-04:00" ), "\n"); MockSession hm = SessionTestUtil.createSession("testWorkspace", contentProperties); ContentMap map = new ContentMap(hm.getNode("/somepage/mypage/paragraphs/0")); assertNotNull(map.get("attachment1")); assertTrue(map.get("attachment1") instanceof ContentMap); } @Test public void testGetOtherProps() throws Exception { String contentProperties = StringUtils.join(Arrays.asList( "/somepage/mypage.@type=mgnl:content", "/somepage/mypage/paragraphs.@type=mgnl:contentNode", "/somepage/mypage/paragraphs/0.@type=mgnl:contentNode", "/somepage/mypage/paragraphs/0.@type=mgnl:contentNode", "/somepage/mypage/paragraphs/0.attention=booyah", "/somepage/mypage/paragraphs/0.imaginary=date:2009-10-14T08:59:01.227-04:00" ), "\n"); MockSession hm = SessionTestUtil.createSession("testWorkspace", contentProperties); ContentMap map = new ContentMap(hm.getNode("/somepage/mypage/paragraphs/0")); assertNotNull(map.get("imaginary")); assertTrue(map.get("imaginary") instanceof Calendar); }
NodeUtil { public static boolean hasMixin(Node node, String mixinName) throws RepositoryException { if (StringUtils.isBlank(mixinName)) { throw new IllegalArgumentException("Mixin name can't be empty."); } for (NodeType type : node.getMixinNodeTypes()) { if (mixinName.equals(type.getName())) { return true; } } return false; } static Node getNodeByIdentifier(String workspace, String identifier); static boolean hasMixin(Node node, String mixinName); static boolean isNodeType(Node node, String type); static Node unwrap(Node node); static Node deepUnwrap(Node node, Class<? extends DelegateNodeWrapper> wrapper); static Node deepUnwrapAll(Node node, Class<? extends DelegateNodeWrapper> wrapperClass); static boolean isWrappedWith(Node node, Class<? extends DelegateNodeWrapper> wrapper); static void orderBefore(Node node, String siblingName); static void orderAfter(Node node, String siblingName); static void orderFirst(Node node); static void orderLast(Node node); static void orderNodeUp(Node node); static void orderNodeDown(Node node); static Node getSiblingBefore(Node node); static Node getSiblingAfter(Node node); static Iterable<Node> getSiblings(Node node); static Iterable<Node> getSiblings(Node node, String nodeTypeName); static Iterable<Node> getSiblings(Node node, Predicate predicate); static Iterable<Node> getSiblingsBefore(Node node); static Iterable<Node> getSiblingsAfter(Node node); static Iterable<Node> getSiblingsBefore(Node node, String nodeTypeName); static Iterable<Node> getSiblingsAfter(Node node, String nodeTypeName); static void moveNode(Node nodeToMove, Node newParent); static void moveNodeBefore(Node nodeToMove, Node target); static void moveNodeAfter(Node nodeToMove, Node target); static boolean isFirstSibling(Node node); static boolean isSameNameSiblings(Node node1, Node node2); static boolean isLastSibling(Node node); static void renameNode(Node node, String newName); static boolean isGranted(Node node, long permissions); static boolean isSame(Node lhs, Node rhs); static String combinePathAndName(String path, String name); static Node createPath(Node parent, String relPath, String primaryNodeTypeName); static Node createPath(Node parent, String relPath, String primaryNodeTypeName, boolean save); static void visit(Node node, NodeVisitor visitor); static void visit(Node node, NodeVisitor visitor, Predicate predicate); static Iterable<Node> getNodes(Node parent, Predicate predicate); static Iterable<Node> getNodes(Node parent); static Iterable<Node> getNodes(Node parent, String nodeTypeName); static Iterable<Node> asIterable(NodeIterator iterator); static List<Node> asList(Iterable<Node> nodes); static String getName(Node content); static Iterable<Node> collectAllChildren(Node node); static Iterable<Node> collectAllChildren(Node node, Predicate predicate); static Iterable<Node> collectAllChildren(List<Node> nodes, Node parent, Predicate predicate); static Collection<Node> getAncestors(Node node); static String getNodeIdentifierIfPossible(Node content); static String getNodePathIfPossible(Node node); static String getPathIfPossible(Node node); static NodeIterator filterNodeType(NodeIterator iterator, String nodeType); static NodeIterator filterDuplicates(NodeIterator iterator); static NodeIterator filterParentNodeType(NodeIterator iterator, final String nodeType); static Collection<Node> getCollectionFromNodeIterator(NodeIterator iterator); static Collection<Node> getSortedCollectionFromNodeIterator(NodeIterator iterator); static void traceNodeProperties(Node nodeOp); static void traceNodeChildren(Node nodeOp); static AbstractPredicate<Property> ALL_PROPERTIES_EXCEPT_JCR_AND_MGNL_FILTER; static Predicate ALL_NODES_EXCEPT_JCR_FILTER; static AbstractPredicate<Node> EXCLUDE_META_DATA_FILTER; static AbstractPredicate<Node> MAGNOLIA_FILTER; }
@Test public void testHasMixin() throws Exception { final String mixin1 = "mixin1"; root.addMixin(mixin1); assertTrue(NodeUtil.hasMixin(root, mixin1)); assertFalse(NodeUtil.hasMixin(root, "mixin2")); } @Test(expected = IllegalArgumentException.class) public void testHasMixinFailsWithEmptyMixin() throws Exception { NodeUtil.hasMixin(root, null); }
NodeUtil { public static Node unwrap(Node node) throws RepositoryException { Node unwrappedNode = node; while (unwrappedNode instanceof DelegateNodeWrapper) { unwrappedNode = ((DelegateNodeWrapper) unwrappedNode).getWrappedNode(); } return unwrappedNode; } static Node getNodeByIdentifier(String workspace, String identifier); static boolean hasMixin(Node node, String mixinName); static boolean isNodeType(Node node, String type); static Node unwrap(Node node); static Node deepUnwrap(Node node, Class<? extends DelegateNodeWrapper> wrapper); static Node deepUnwrapAll(Node node, Class<? extends DelegateNodeWrapper> wrapperClass); static boolean isWrappedWith(Node node, Class<? extends DelegateNodeWrapper> wrapper); static void orderBefore(Node node, String siblingName); static void orderAfter(Node node, String siblingName); static void orderFirst(Node node); static void orderLast(Node node); static void orderNodeUp(Node node); static void orderNodeDown(Node node); static Node getSiblingBefore(Node node); static Node getSiblingAfter(Node node); static Iterable<Node> getSiblings(Node node); static Iterable<Node> getSiblings(Node node, String nodeTypeName); static Iterable<Node> getSiblings(Node node, Predicate predicate); static Iterable<Node> getSiblingsBefore(Node node); static Iterable<Node> getSiblingsAfter(Node node); static Iterable<Node> getSiblingsBefore(Node node, String nodeTypeName); static Iterable<Node> getSiblingsAfter(Node node, String nodeTypeName); static void moveNode(Node nodeToMove, Node newParent); static void moveNodeBefore(Node nodeToMove, Node target); static void moveNodeAfter(Node nodeToMove, Node target); static boolean isFirstSibling(Node node); static boolean isSameNameSiblings(Node node1, Node node2); static boolean isLastSibling(Node node); static void renameNode(Node node, String newName); static boolean isGranted(Node node, long permissions); static boolean isSame(Node lhs, Node rhs); static String combinePathAndName(String path, String name); static Node createPath(Node parent, String relPath, String primaryNodeTypeName); static Node createPath(Node parent, String relPath, String primaryNodeTypeName, boolean save); static void visit(Node node, NodeVisitor visitor); static void visit(Node node, NodeVisitor visitor, Predicate predicate); static Iterable<Node> getNodes(Node parent, Predicate predicate); static Iterable<Node> getNodes(Node parent); static Iterable<Node> getNodes(Node parent, String nodeTypeName); static Iterable<Node> asIterable(NodeIterator iterator); static List<Node> asList(Iterable<Node> nodes); static String getName(Node content); static Iterable<Node> collectAllChildren(Node node); static Iterable<Node> collectAllChildren(Node node, Predicate predicate); static Iterable<Node> collectAllChildren(List<Node> nodes, Node parent, Predicate predicate); static Collection<Node> getAncestors(Node node); static String getNodeIdentifierIfPossible(Node content); static String getNodePathIfPossible(Node node); static String getPathIfPossible(Node node); static NodeIterator filterNodeType(NodeIterator iterator, String nodeType); static NodeIterator filterDuplicates(NodeIterator iterator); static NodeIterator filterParentNodeType(NodeIterator iterator, final String nodeType); static Collection<Node> getCollectionFromNodeIterator(NodeIterator iterator); static Collection<Node> getSortedCollectionFromNodeIterator(NodeIterator iterator); static void traceNodeProperties(Node nodeOp); static void traceNodeChildren(Node nodeOp); static AbstractPredicate<Property> ALL_PROPERTIES_EXCEPT_JCR_AND_MGNL_FILTER; static Predicate ALL_NODES_EXCEPT_JCR_FILTER; static AbstractPredicate<Node> EXCLUDE_META_DATA_FILTER; static AbstractPredicate<Node> MAGNOLIA_FILTER; }
@Test public void testUnwrap() throws Exception { final Version version = mock(Version.class); when(version.getNode(JcrConstants.JCR_FROZENNODE)).thenReturn(root); final VersionedNode wrapper = new VersionedNode(version, root); assertEquals(root, NodeUtil.unwrap(wrapper)); }
NodeUtil { public static void orderFirst(Node node) throws RepositoryException { Node parent = node.getParent(); NodeIterator siblings = parent.getNodes(); Node firstSibling = siblings.nextNode(); if (!firstSibling.isSame(node)) { parent.orderBefore(node.getName(), firstSibling.getName()); } } static Node getNodeByIdentifier(String workspace, String identifier); static boolean hasMixin(Node node, String mixinName); static boolean isNodeType(Node node, String type); static Node unwrap(Node node); static Node deepUnwrap(Node node, Class<? extends DelegateNodeWrapper> wrapper); static Node deepUnwrapAll(Node node, Class<? extends DelegateNodeWrapper> wrapperClass); static boolean isWrappedWith(Node node, Class<? extends DelegateNodeWrapper> wrapper); static void orderBefore(Node node, String siblingName); static void orderAfter(Node node, String siblingName); static void orderFirst(Node node); static void orderLast(Node node); static void orderNodeUp(Node node); static void orderNodeDown(Node node); static Node getSiblingBefore(Node node); static Node getSiblingAfter(Node node); static Iterable<Node> getSiblings(Node node); static Iterable<Node> getSiblings(Node node, String nodeTypeName); static Iterable<Node> getSiblings(Node node, Predicate predicate); static Iterable<Node> getSiblingsBefore(Node node); static Iterable<Node> getSiblingsAfter(Node node); static Iterable<Node> getSiblingsBefore(Node node, String nodeTypeName); static Iterable<Node> getSiblingsAfter(Node node, String nodeTypeName); static void moveNode(Node nodeToMove, Node newParent); static void moveNodeBefore(Node nodeToMove, Node target); static void moveNodeAfter(Node nodeToMove, Node target); static boolean isFirstSibling(Node node); static boolean isSameNameSiblings(Node node1, Node node2); static boolean isLastSibling(Node node); static void renameNode(Node node, String newName); static boolean isGranted(Node node, long permissions); static boolean isSame(Node lhs, Node rhs); static String combinePathAndName(String path, String name); static Node createPath(Node parent, String relPath, String primaryNodeTypeName); static Node createPath(Node parent, String relPath, String primaryNodeTypeName, boolean save); static void visit(Node node, NodeVisitor visitor); static void visit(Node node, NodeVisitor visitor, Predicate predicate); static Iterable<Node> getNodes(Node parent, Predicate predicate); static Iterable<Node> getNodes(Node parent); static Iterable<Node> getNodes(Node parent, String nodeTypeName); static Iterable<Node> asIterable(NodeIterator iterator); static List<Node> asList(Iterable<Node> nodes); static String getName(Node content); static Iterable<Node> collectAllChildren(Node node); static Iterable<Node> collectAllChildren(Node node, Predicate predicate); static Iterable<Node> collectAllChildren(List<Node> nodes, Node parent, Predicate predicate); static Collection<Node> getAncestors(Node node); static String getNodeIdentifierIfPossible(Node content); static String getNodePathIfPossible(Node node); static String getPathIfPossible(Node node); static NodeIterator filterNodeType(NodeIterator iterator, String nodeType); static NodeIterator filterDuplicates(NodeIterator iterator); static NodeIterator filterParentNodeType(NodeIterator iterator, final String nodeType); static Collection<Node> getCollectionFromNodeIterator(NodeIterator iterator); static Collection<Node> getSortedCollectionFromNodeIterator(NodeIterator iterator); static void traceNodeProperties(Node nodeOp); static void traceNodeChildren(Node nodeOp); static AbstractPredicate<Property> ALL_PROPERTIES_EXCEPT_JCR_AND_MGNL_FILTER; static Predicate ALL_NODES_EXCEPT_JCR_FILTER; static AbstractPredicate<Node> EXCLUDE_META_DATA_FILTER; static AbstractPredicate<Node> MAGNOLIA_FILTER; }
@Test public void testOrderFirst() throws RepositoryException { NodeUtil.orderFirst(second); NodeIterator orderedKids = root.getNodes(); assertEquals(second, orderedKids.next()); assertEquals(first, orderedKids.next()); assertEquals(third, orderedKids.next()); }
NodeUtil { public static void orderLast(Node node) throws RepositoryException { node.getParent().orderBefore(node.getName(), null); } static Node getNodeByIdentifier(String workspace, String identifier); static boolean hasMixin(Node node, String mixinName); static boolean isNodeType(Node node, String type); static Node unwrap(Node node); static Node deepUnwrap(Node node, Class<? extends DelegateNodeWrapper> wrapper); static Node deepUnwrapAll(Node node, Class<? extends DelegateNodeWrapper> wrapperClass); static boolean isWrappedWith(Node node, Class<? extends DelegateNodeWrapper> wrapper); static void orderBefore(Node node, String siblingName); static void orderAfter(Node node, String siblingName); static void orderFirst(Node node); static void orderLast(Node node); static void orderNodeUp(Node node); static void orderNodeDown(Node node); static Node getSiblingBefore(Node node); static Node getSiblingAfter(Node node); static Iterable<Node> getSiblings(Node node); static Iterable<Node> getSiblings(Node node, String nodeTypeName); static Iterable<Node> getSiblings(Node node, Predicate predicate); static Iterable<Node> getSiblingsBefore(Node node); static Iterable<Node> getSiblingsAfter(Node node); static Iterable<Node> getSiblingsBefore(Node node, String nodeTypeName); static Iterable<Node> getSiblingsAfter(Node node, String nodeTypeName); static void moveNode(Node nodeToMove, Node newParent); static void moveNodeBefore(Node nodeToMove, Node target); static void moveNodeAfter(Node nodeToMove, Node target); static boolean isFirstSibling(Node node); static boolean isSameNameSiblings(Node node1, Node node2); static boolean isLastSibling(Node node); static void renameNode(Node node, String newName); static boolean isGranted(Node node, long permissions); static boolean isSame(Node lhs, Node rhs); static String combinePathAndName(String path, String name); static Node createPath(Node parent, String relPath, String primaryNodeTypeName); static Node createPath(Node parent, String relPath, String primaryNodeTypeName, boolean save); static void visit(Node node, NodeVisitor visitor); static void visit(Node node, NodeVisitor visitor, Predicate predicate); static Iterable<Node> getNodes(Node parent, Predicate predicate); static Iterable<Node> getNodes(Node parent); static Iterable<Node> getNodes(Node parent, String nodeTypeName); static Iterable<Node> asIterable(NodeIterator iterator); static List<Node> asList(Iterable<Node> nodes); static String getName(Node content); static Iterable<Node> collectAllChildren(Node node); static Iterable<Node> collectAllChildren(Node node, Predicate predicate); static Iterable<Node> collectAllChildren(List<Node> nodes, Node parent, Predicate predicate); static Collection<Node> getAncestors(Node node); static String getNodeIdentifierIfPossible(Node content); static String getNodePathIfPossible(Node node); static String getPathIfPossible(Node node); static NodeIterator filterNodeType(NodeIterator iterator, String nodeType); static NodeIterator filterDuplicates(NodeIterator iterator); static NodeIterator filterParentNodeType(NodeIterator iterator, final String nodeType); static Collection<Node> getCollectionFromNodeIterator(NodeIterator iterator); static Collection<Node> getSortedCollectionFromNodeIterator(NodeIterator iterator); static void traceNodeProperties(Node nodeOp); static void traceNodeChildren(Node nodeOp); static AbstractPredicate<Property> ALL_PROPERTIES_EXCEPT_JCR_AND_MGNL_FILTER; static Predicate ALL_NODES_EXCEPT_JCR_FILTER; static AbstractPredicate<Node> EXCLUDE_META_DATA_FILTER; static AbstractPredicate<Node> MAGNOLIA_FILTER; }
@Test public void testOrderLast() throws RepositoryException { NodeUtil.orderLast(second); NodeIterator orderedKids = root.getNodes(); assertEquals(first, orderedKids.next()); assertEquals(third, orderedKids.next()); assertEquals(second, orderedKids.next()); }
NodeUtil { public static Node createPath(Node parent, String relPath, String primaryNodeTypeName) throws RepositoryException, PathNotFoundException, AccessDeniedException { return createPath(parent, relPath, primaryNodeTypeName, false); } static Node getNodeByIdentifier(String workspace, String identifier); static boolean hasMixin(Node node, String mixinName); static boolean isNodeType(Node node, String type); static Node unwrap(Node node); static Node deepUnwrap(Node node, Class<? extends DelegateNodeWrapper> wrapper); static Node deepUnwrapAll(Node node, Class<? extends DelegateNodeWrapper> wrapperClass); static boolean isWrappedWith(Node node, Class<? extends DelegateNodeWrapper> wrapper); static void orderBefore(Node node, String siblingName); static void orderAfter(Node node, String siblingName); static void orderFirst(Node node); static void orderLast(Node node); static void orderNodeUp(Node node); static void orderNodeDown(Node node); static Node getSiblingBefore(Node node); static Node getSiblingAfter(Node node); static Iterable<Node> getSiblings(Node node); static Iterable<Node> getSiblings(Node node, String nodeTypeName); static Iterable<Node> getSiblings(Node node, Predicate predicate); static Iterable<Node> getSiblingsBefore(Node node); static Iterable<Node> getSiblingsAfter(Node node); static Iterable<Node> getSiblingsBefore(Node node, String nodeTypeName); static Iterable<Node> getSiblingsAfter(Node node, String nodeTypeName); static void moveNode(Node nodeToMove, Node newParent); static void moveNodeBefore(Node nodeToMove, Node target); static void moveNodeAfter(Node nodeToMove, Node target); static boolean isFirstSibling(Node node); static boolean isSameNameSiblings(Node node1, Node node2); static boolean isLastSibling(Node node); static void renameNode(Node node, String newName); static boolean isGranted(Node node, long permissions); static boolean isSame(Node lhs, Node rhs); static String combinePathAndName(String path, String name); static Node createPath(Node parent, String relPath, String primaryNodeTypeName); static Node createPath(Node parent, String relPath, String primaryNodeTypeName, boolean save); static void visit(Node node, NodeVisitor visitor); static void visit(Node node, NodeVisitor visitor, Predicate predicate); static Iterable<Node> getNodes(Node parent, Predicate predicate); static Iterable<Node> getNodes(Node parent); static Iterable<Node> getNodes(Node parent, String nodeTypeName); static Iterable<Node> asIterable(NodeIterator iterator); static List<Node> asList(Iterable<Node> nodes); static String getName(Node content); static Iterable<Node> collectAllChildren(Node node); static Iterable<Node> collectAllChildren(Node node, Predicate predicate); static Iterable<Node> collectAllChildren(List<Node> nodes, Node parent, Predicate predicate); static Collection<Node> getAncestors(Node node); static String getNodeIdentifierIfPossible(Node content); static String getNodePathIfPossible(Node node); static String getPathIfPossible(Node node); static NodeIterator filterNodeType(NodeIterator iterator, String nodeType); static NodeIterator filterDuplicates(NodeIterator iterator); static NodeIterator filterParentNodeType(NodeIterator iterator, final String nodeType); static Collection<Node> getCollectionFromNodeIterator(NodeIterator iterator); static Collection<Node> getSortedCollectionFromNodeIterator(NodeIterator iterator); static void traceNodeProperties(Node nodeOp); static void traceNodeChildren(Node nodeOp); static AbstractPredicate<Property> ALL_PROPERTIES_EXCEPT_JCR_AND_MGNL_FILTER; static Predicate ALL_NODES_EXCEPT_JCR_FILTER; static AbstractPredicate<Node> EXCLUDE_META_DATA_FILTER; static AbstractPredicate<Node> MAGNOLIA_FILTER; }
@Test public void testCreatePath() throws RepositoryException { final String pathToCreate = "/xxx/yyy/zzz"; Node zzz = NodeUtil.createPath(root, pathToCreate, PropertyType.TYPENAME_STRING); assertNotNull(zzz); assertEquals(PropertyType.TYPENAME_STRING, zzz.getPrimaryNodeType().getName()); } @Test public void testCreatePathDoesntCreateNewWhenExisting() throws RepositoryException { Node returnedNode = NodeUtil.createPath(root, FIRST_CHILD, PropertyType.TYPENAME_STRING); assertNotNull(returnedNode); assertEquals("createPath was called with existing subpath: existing node should be returned - not a new instance!", first, returnedNode); }
NodeUtil { public static void visit(Node node, NodeVisitor visitor) throws RepositoryException { visit(node, visitor, EXCLUDE_META_DATA_FILTER); } static Node getNodeByIdentifier(String workspace, String identifier); static boolean hasMixin(Node node, String mixinName); static boolean isNodeType(Node node, String type); static Node unwrap(Node node); static Node deepUnwrap(Node node, Class<? extends DelegateNodeWrapper> wrapper); static Node deepUnwrapAll(Node node, Class<? extends DelegateNodeWrapper> wrapperClass); static boolean isWrappedWith(Node node, Class<? extends DelegateNodeWrapper> wrapper); static void orderBefore(Node node, String siblingName); static void orderAfter(Node node, String siblingName); static void orderFirst(Node node); static void orderLast(Node node); static void orderNodeUp(Node node); static void orderNodeDown(Node node); static Node getSiblingBefore(Node node); static Node getSiblingAfter(Node node); static Iterable<Node> getSiblings(Node node); static Iterable<Node> getSiblings(Node node, String nodeTypeName); static Iterable<Node> getSiblings(Node node, Predicate predicate); static Iterable<Node> getSiblingsBefore(Node node); static Iterable<Node> getSiblingsAfter(Node node); static Iterable<Node> getSiblingsBefore(Node node, String nodeTypeName); static Iterable<Node> getSiblingsAfter(Node node, String nodeTypeName); static void moveNode(Node nodeToMove, Node newParent); static void moveNodeBefore(Node nodeToMove, Node target); static void moveNodeAfter(Node nodeToMove, Node target); static boolean isFirstSibling(Node node); static boolean isSameNameSiblings(Node node1, Node node2); static boolean isLastSibling(Node node); static void renameNode(Node node, String newName); static boolean isGranted(Node node, long permissions); static boolean isSame(Node lhs, Node rhs); static String combinePathAndName(String path, String name); static Node createPath(Node parent, String relPath, String primaryNodeTypeName); static Node createPath(Node parent, String relPath, String primaryNodeTypeName, boolean save); static void visit(Node node, NodeVisitor visitor); static void visit(Node node, NodeVisitor visitor, Predicate predicate); static Iterable<Node> getNodes(Node parent, Predicate predicate); static Iterable<Node> getNodes(Node parent); static Iterable<Node> getNodes(Node parent, String nodeTypeName); static Iterable<Node> asIterable(NodeIterator iterator); static List<Node> asList(Iterable<Node> nodes); static String getName(Node content); static Iterable<Node> collectAllChildren(Node node); static Iterable<Node> collectAllChildren(Node node, Predicate predicate); static Iterable<Node> collectAllChildren(List<Node> nodes, Node parent, Predicate predicate); static Collection<Node> getAncestors(Node node); static String getNodeIdentifierIfPossible(Node content); static String getNodePathIfPossible(Node node); static String getPathIfPossible(Node node); static NodeIterator filterNodeType(NodeIterator iterator, String nodeType); static NodeIterator filterDuplicates(NodeIterator iterator); static NodeIterator filterParentNodeType(NodeIterator iterator, final String nodeType); static Collection<Node> getCollectionFromNodeIterator(NodeIterator iterator); static Collection<Node> getSortedCollectionFromNodeIterator(NodeIterator iterator); static void traceNodeProperties(Node nodeOp); static void traceNodeChildren(Node nodeOp); static AbstractPredicate<Property> ALL_PROPERTIES_EXCEPT_JCR_AND_MGNL_FILTER; static Predicate ALL_NODES_EXCEPT_JCR_FILTER; static AbstractPredicate<Node> EXCLUDE_META_DATA_FILTER; static AbstractPredicate<Node> MAGNOLIA_FILTER; }
@Test public void testVisit() throws RepositoryException { final AtomicInteger counter = new AtomicInteger(0); NodeUtil.visit(root, new NodeVisitor() { @Override public void visit(Node node) throws RepositoryException { counter.incrementAndGet(); } }); assertEquals(4, counter.get()); }
NodeUtil { public static Iterable<Node> getNodes(Node parent, Predicate predicate) throws RepositoryException { return asIterable(new FilteringNodeIterator(parent.getNodes(), predicate)); } static Node getNodeByIdentifier(String workspace, String identifier); static boolean hasMixin(Node node, String mixinName); static boolean isNodeType(Node node, String type); static Node unwrap(Node node); static Node deepUnwrap(Node node, Class<? extends DelegateNodeWrapper> wrapper); static Node deepUnwrapAll(Node node, Class<? extends DelegateNodeWrapper> wrapperClass); static boolean isWrappedWith(Node node, Class<? extends DelegateNodeWrapper> wrapper); static void orderBefore(Node node, String siblingName); static void orderAfter(Node node, String siblingName); static void orderFirst(Node node); static void orderLast(Node node); static void orderNodeUp(Node node); static void orderNodeDown(Node node); static Node getSiblingBefore(Node node); static Node getSiblingAfter(Node node); static Iterable<Node> getSiblings(Node node); static Iterable<Node> getSiblings(Node node, String nodeTypeName); static Iterable<Node> getSiblings(Node node, Predicate predicate); static Iterable<Node> getSiblingsBefore(Node node); static Iterable<Node> getSiblingsAfter(Node node); static Iterable<Node> getSiblingsBefore(Node node, String nodeTypeName); static Iterable<Node> getSiblingsAfter(Node node, String nodeTypeName); static void moveNode(Node nodeToMove, Node newParent); static void moveNodeBefore(Node nodeToMove, Node target); static void moveNodeAfter(Node nodeToMove, Node target); static boolean isFirstSibling(Node node); static boolean isSameNameSiblings(Node node1, Node node2); static boolean isLastSibling(Node node); static void renameNode(Node node, String newName); static boolean isGranted(Node node, long permissions); static boolean isSame(Node lhs, Node rhs); static String combinePathAndName(String path, String name); static Node createPath(Node parent, String relPath, String primaryNodeTypeName); static Node createPath(Node parent, String relPath, String primaryNodeTypeName, boolean save); static void visit(Node node, NodeVisitor visitor); static void visit(Node node, NodeVisitor visitor, Predicate predicate); static Iterable<Node> getNodes(Node parent, Predicate predicate); static Iterable<Node> getNodes(Node parent); static Iterable<Node> getNodes(Node parent, String nodeTypeName); static Iterable<Node> asIterable(NodeIterator iterator); static List<Node> asList(Iterable<Node> nodes); static String getName(Node content); static Iterable<Node> collectAllChildren(Node node); static Iterable<Node> collectAllChildren(Node node, Predicate predicate); static Iterable<Node> collectAllChildren(List<Node> nodes, Node parent, Predicate predicate); static Collection<Node> getAncestors(Node node); static String getNodeIdentifierIfPossible(Node content); static String getNodePathIfPossible(Node node); static String getPathIfPossible(Node node); static NodeIterator filterNodeType(NodeIterator iterator, String nodeType); static NodeIterator filterDuplicates(NodeIterator iterator); static NodeIterator filterParentNodeType(NodeIterator iterator, final String nodeType); static Collection<Node> getCollectionFromNodeIterator(NodeIterator iterator); static Collection<Node> getSortedCollectionFromNodeIterator(NodeIterator iterator); static void traceNodeProperties(Node nodeOp); static void traceNodeChildren(Node nodeOp); static AbstractPredicate<Property> ALL_PROPERTIES_EXCEPT_JCR_AND_MGNL_FILTER; static Predicate ALL_NODES_EXCEPT_JCR_FILTER; static AbstractPredicate<Node> EXCLUDE_META_DATA_FILTER; static AbstractPredicate<Node> MAGNOLIA_FILTER; }
@Test public void testGetNodes() throws RepositoryException { first.addNode("alpha", NodeTypes.Content.NAME); first.addNode("meta", NodeTypes.MetaData.NAME); first.addNode("gamma", NodeTypes.Content.NAME); Iterable<Node> iterable = NodeUtil.getNodes(first); Iterator<Node> iterator = iterable.iterator(); assertEquals("alpha", iterator.next().getName()); assertEquals("gamma", iterator.next().getName()); assertTrue(!iterator.hasNext()); }
NodeUtil { public static String getName(Node content) { try { return content.getName(); } catch (RepositoryException e) { throw new RuntimeRepositoryException(e); } } static Node getNodeByIdentifier(String workspace, String identifier); static boolean hasMixin(Node node, String mixinName); static boolean isNodeType(Node node, String type); static Node unwrap(Node node); static Node deepUnwrap(Node node, Class<? extends DelegateNodeWrapper> wrapper); static Node deepUnwrapAll(Node node, Class<? extends DelegateNodeWrapper> wrapperClass); static boolean isWrappedWith(Node node, Class<? extends DelegateNodeWrapper> wrapper); static void orderBefore(Node node, String siblingName); static void orderAfter(Node node, String siblingName); static void orderFirst(Node node); static void orderLast(Node node); static void orderNodeUp(Node node); static void orderNodeDown(Node node); static Node getSiblingBefore(Node node); static Node getSiblingAfter(Node node); static Iterable<Node> getSiblings(Node node); static Iterable<Node> getSiblings(Node node, String nodeTypeName); static Iterable<Node> getSiblings(Node node, Predicate predicate); static Iterable<Node> getSiblingsBefore(Node node); static Iterable<Node> getSiblingsAfter(Node node); static Iterable<Node> getSiblingsBefore(Node node, String nodeTypeName); static Iterable<Node> getSiblingsAfter(Node node, String nodeTypeName); static void moveNode(Node nodeToMove, Node newParent); static void moveNodeBefore(Node nodeToMove, Node target); static void moveNodeAfter(Node nodeToMove, Node target); static boolean isFirstSibling(Node node); static boolean isSameNameSiblings(Node node1, Node node2); static boolean isLastSibling(Node node); static void renameNode(Node node, String newName); static boolean isGranted(Node node, long permissions); static boolean isSame(Node lhs, Node rhs); static String combinePathAndName(String path, String name); static Node createPath(Node parent, String relPath, String primaryNodeTypeName); static Node createPath(Node parent, String relPath, String primaryNodeTypeName, boolean save); static void visit(Node node, NodeVisitor visitor); static void visit(Node node, NodeVisitor visitor, Predicate predicate); static Iterable<Node> getNodes(Node parent, Predicate predicate); static Iterable<Node> getNodes(Node parent); static Iterable<Node> getNodes(Node parent, String nodeTypeName); static Iterable<Node> asIterable(NodeIterator iterator); static List<Node> asList(Iterable<Node> nodes); static String getName(Node content); static Iterable<Node> collectAllChildren(Node node); static Iterable<Node> collectAllChildren(Node node, Predicate predicate); static Iterable<Node> collectAllChildren(List<Node> nodes, Node parent, Predicate predicate); static Collection<Node> getAncestors(Node node); static String getNodeIdentifierIfPossible(Node content); static String getNodePathIfPossible(Node node); static String getPathIfPossible(Node node); static NodeIterator filterNodeType(NodeIterator iterator, String nodeType); static NodeIterator filterDuplicates(NodeIterator iterator); static NodeIterator filterParentNodeType(NodeIterator iterator, final String nodeType); static Collection<Node> getCollectionFromNodeIterator(NodeIterator iterator); static Collection<Node> getSortedCollectionFromNodeIterator(NodeIterator iterator); static void traceNodeProperties(Node nodeOp); static void traceNodeChildren(Node nodeOp); static AbstractPredicate<Property> ALL_PROPERTIES_EXCEPT_JCR_AND_MGNL_FILTER; static Predicate ALL_NODES_EXCEPT_JCR_FILTER; static AbstractPredicate<Node> EXCLUDE_META_DATA_FILTER; static AbstractPredicate<Node> MAGNOLIA_FILTER; }
@Test public void testGetNameFromNode() { assertEquals(FIRST_CHILD, NodeUtil.getName(first)); } @Test(expected = RuntimeRepositoryException.class) public void testGetNameFromNodeThrowsRuntimeRepositoryException() { Node node = mock(Node.class); try { when(node.getName()).thenThrow(new RepositoryException()); } catch (RepositoryException e) { fail(); } NodeUtil.getName(node); }
NodeUtil { public static Node getNodeByIdentifier(String workspace, String identifier) throws RepositoryException { Node target = null; Session jcrSession; if (workspace == null || identifier == null) { return target; } jcrSession = MgnlContext.getJCRSession(workspace); if (jcrSession != null) { target = jcrSession.getNodeByIdentifier(identifier); } return target; } static Node getNodeByIdentifier(String workspace, String identifier); static boolean hasMixin(Node node, String mixinName); static boolean isNodeType(Node node, String type); static Node unwrap(Node node); static Node deepUnwrap(Node node, Class<? extends DelegateNodeWrapper> wrapper); static Node deepUnwrapAll(Node node, Class<? extends DelegateNodeWrapper> wrapperClass); static boolean isWrappedWith(Node node, Class<? extends DelegateNodeWrapper> wrapper); static void orderBefore(Node node, String siblingName); static void orderAfter(Node node, String siblingName); static void orderFirst(Node node); static void orderLast(Node node); static void orderNodeUp(Node node); static void orderNodeDown(Node node); static Node getSiblingBefore(Node node); static Node getSiblingAfter(Node node); static Iterable<Node> getSiblings(Node node); static Iterable<Node> getSiblings(Node node, String nodeTypeName); static Iterable<Node> getSiblings(Node node, Predicate predicate); static Iterable<Node> getSiblingsBefore(Node node); static Iterable<Node> getSiblingsAfter(Node node); static Iterable<Node> getSiblingsBefore(Node node, String nodeTypeName); static Iterable<Node> getSiblingsAfter(Node node, String nodeTypeName); static void moveNode(Node nodeToMove, Node newParent); static void moveNodeBefore(Node nodeToMove, Node target); static void moveNodeAfter(Node nodeToMove, Node target); static boolean isFirstSibling(Node node); static boolean isSameNameSiblings(Node node1, Node node2); static boolean isLastSibling(Node node); static void renameNode(Node node, String newName); static boolean isGranted(Node node, long permissions); static boolean isSame(Node lhs, Node rhs); static String combinePathAndName(String path, String name); static Node createPath(Node parent, String relPath, String primaryNodeTypeName); static Node createPath(Node parent, String relPath, String primaryNodeTypeName, boolean save); static void visit(Node node, NodeVisitor visitor); static void visit(Node node, NodeVisitor visitor, Predicate predicate); static Iterable<Node> getNodes(Node parent, Predicate predicate); static Iterable<Node> getNodes(Node parent); static Iterable<Node> getNodes(Node parent, String nodeTypeName); static Iterable<Node> asIterable(NodeIterator iterator); static List<Node> asList(Iterable<Node> nodes); static String getName(Node content); static Iterable<Node> collectAllChildren(Node node); static Iterable<Node> collectAllChildren(Node node, Predicate predicate); static Iterable<Node> collectAllChildren(List<Node> nodes, Node parent, Predicate predicate); static Collection<Node> getAncestors(Node node); static String getNodeIdentifierIfPossible(Node content); static String getNodePathIfPossible(Node node); static String getPathIfPossible(Node node); static NodeIterator filterNodeType(NodeIterator iterator, String nodeType); static NodeIterator filterDuplicates(NodeIterator iterator); static NodeIterator filterParentNodeType(NodeIterator iterator, final String nodeType); static Collection<Node> getCollectionFromNodeIterator(NodeIterator iterator); static Collection<Node> getSortedCollectionFromNodeIterator(NodeIterator iterator); static void traceNodeProperties(Node nodeOp); static void traceNodeChildren(Node nodeOp); static AbstractPredicate<Property> ALL_PROPERTIES_EXCEPT_JCR_AND_MGNL_FILTER; static Predicate ALL_NODES_EXCEPT_JCR_FILTER; static AbstractPredicate<Node> EXCLUDE_META_DATA_FILTER; static AbstractPredicate<Node> MAGNOLIA_FILTER; }
@Test public void testGetNodeByIdentifier() throws RepositoryException { try { MockUtil.initMockContext(); MockSession session = new MockSession("website"); MockUtil.setSessionAndHierarchyManager(session); Node rootNode = session.getRootNode(); Node addedNode = rootNode.addNode(FIRST_CHILD); String identifier = addedNode.getIdentifier(); Node res = NodeUtil.getNodeByIdentifier("website", identifier); assertEquals("Both Node should be Identical ", addedNode, res); } finally { MgnlContext.setInstance(null); } } @Test public void testGetNodeByIdentifierMissingParam() throws RepositoryException { try { Node res = NodeUtil.getNodeByIdentifier("website", null); assertEquals("Both Node should be Identical ", null, res); } finally { MgnlContext.setInstance(null); } } @Test(expected = RepositoryException.class) public void testGetNodeByIdentifierNoNodeFound() throws RepositoryException { try { MockUtil.initMockContext(); MockSession session = new MockSession("website"); MockUtil.setSessionAndHierarchyManager(session); Node rootNode = session.getRootNode(); Node addedNode = rootNode.addNode(FIRST_CHILD); String identifier = addedNode.getIdentifier(); NodeUtil.getNodeByIdentifier("website", identifier + 1); assertTrue("Should get an Exception ", false); } finally { MgnlContext.setInstance(null); } }
NodeUtil { public static String getPathIfPossible(Node node) { try { return node.getPath(); } catch (RepositoryException e) { log.error("Failed to get handle: " + e.getMessage(), e); return StringUtils.EMPTY; } } static Node getNodeByIdentifier(String workspace, String identifier); static boolean hasMixin(Node node, String mixinName); static boolean isNodeType(Node node, String type); static Node unwrap(Node node); static Node deepUnwrap(Node node, Class<? extends DelegateNodeWrapper> wrapper); static Node deepUnwrapAll(Node node, Class<? extends DelegateNodeWrapper> wrapperClass); static boolean isWrappedWith(Node node, Class<? extends DelegateNodeWrapper> wrapper); static void orderBefore(Node node, String siblingName); static void orderAfter(Node node, String siblingName); static void orderFirst(Node node); static void orderLast(Node node); static void orderNodeUp(Node node); static void orderNodeDown(Node node); static Node getSiblingBefore(Node node); static Node getSiblingAfter(Node node); static Iterable<Node> getSiblings(Node node); static Iterable<Node> getSiblings(Node node, String nodeTypeName); static Iterable<Node> getSiblings(Node node, Predicate predicate); static Iterable<Node> getSiblingsBefore(Node node); static Iterable<Node> getSiblingsAfter(Node node); static Iterable<Node> getSiblingsBefore(Node node, String nodeTypeName); static Iterable<Node> getSiblingsAfter(Node node, String nodeTypeName); static void moveNode(Node nodeToMove, Node newParent); static void moveNodeBefore(Node nodeToMove, Node target); static void moveNodeAfter(Node nodeToMove, Node target); static boolean isFirstSibling(Node node); static boolean isSameNameSiblings(Node node1, Node node2); static boolean isLastSibling(Node node); static void renameNode(Node node, String newName); static boolean isGranted(Node node, long permissions); static boolean isSame(Node lhs, Node rhs); static String combinePathAndName(String path, String name); static Node createPath(Node parent, String relPath, String primaryNodeTypeName); static Node createPath(Node parent, String relPath, String primaryNodeTypeName, boolean save); static void visit(Node node, NodeVisitor visitor); static void visit(Node node, NodeVisitor visitor, Predicate predicate); static Iterable<Node> getNodes(Node parent, Predicate predicate); static Iterable<Node> getNodes(Node parent); static Iterable<Node> getNodes(Node parent, String nodeTypeName); static Iterable<Node> asIterable(NodeIterator iterator); static List<Node> asList(Iterable<Node> nodes); static String getName(Node content); static Iterable<Node> collectAllChildren(Node node); static Iterable<Node> collectAllChildren(Node node, Predicate predicate); static Iterable<Node> collectAllChildren(List<Node> nodes, Node parent, Predicate predicate); static Collection<Node> getAncestors(Node node); static String getNodeIdentifierIfPossible(Node content); static String getNodePathIfPossible(Node node); static String getPathIfPossible(Node node); static NodeIterator filterNodeType(NodeIterator iterator, String nodeType); static NodeIterator filterDuplicates(NodeIterator iterator); static NodeIterator filterParentNodeType(NodeIterator iterator, final String nodeType); static Collection<Node> getCollectionFromNodeIterator(NodeIterator iterator); static Collection<Node> getSortedCollectionFromNodeIterator(NodeIterator iterator); static void traceNodeProperties(Node nodeOp); static void traceNodeChildren(Node nodeOp); static AbstractPredicate<Property> ALL_PROPERTIES_EXCEPT_JCR_AND_MGNL_FILTER; static Predicate ALL_NODES_EXCEPT_JCR_FILTER; static AbstractPredicate<Node> EXCLUDE_META_DATA_FILTER; static AbstractPredicate<Node> MAGNOLIA_FILTER; }
@Test public void testGetPathIfPossible() { String res = NodeUtil.getPathIfPossible(first); assertEquals("Should be /testNode ", "/" + FIRST_CHILD, res); }
NodeUtil { public static boolean isSameNameSiblings(Node node1, Node node2) throws RepositoryException { Node parent1 = node1.getParent(); Node parent2 = node2.getParent(); return isSame(parent1, parent2) && node1.getName().equals(node2.getName()); } static Node getNodeByIdentifier(String workspace, String identifier); static boolean hasMixin(Node node, String mixinName); static boolean isNodeType(Node node, String type); static Node unwrap(Node node); static Node deepUnwrap(Node node, Class<? extends DelegateNodeWrapper> wrapper); static Node deepUnwrapAll(Node node, Class<? extends DelegateNodeWrapper> wrapperClass); static boolean isWrappedWith(Node node, Class<? extends DelegateNodeWrapper> wrapper); static void orderBefore(Node node, String siblingName); static void orderAfter(Node node, String siblingName); static void orderFirst(Node node); static void orderLast(Node node); static void orderNodeUp(Node node); static void orderNodeDown(Node node); static Node getSiblingBefore(Node node); static Node getSiblingAfter(Node node); static Iterable<Node> getSiblings(Node node); static Iterable<Node> getSiblings(Node node, String nodeTypeName); static Iterable<Node> getSiblings(Node node, Predicate predicate); static Iterable<Node> getSiblingsBefore(Node node); static Iterable<Node> getSiblingsAfter(Node node); static Iterable<Node> getSiblingsBefore(Node node, String nodeTypeName); static Iterable<Node> getSiblingsAfter(Node node, String nodeTypeName); static void moveNode(Node nodeToMove, Node newParent); static void moveNodeBefore(Node nodeToMove, Node target); static void moveNodeAfter(Node nodeToMove, Node target); static boolean isFirstSibling(Node node); static boolean isSameNameSiblings(Node node1, Node node2); static boolean isLastSibling(Node node); static void renameNode(Node node, String newName); static boolean isGranted(Node node, long permissions); static boolean isSame(Node lhs, Node rhs); static String combinePathAndName(String path, String name); static Node createPath(Node parent, String relPath, String primaryNodeTypeName); static Node createPath(Node parent, String relPath, String primaryNodeTypeName, boolean save); static void visit(Node node, NodeVisitor visitor); static void visit(Node node, NodeVisitor visitor, Predicate predicate); static Iterable<Node> getNodes(Node parent, Predicate predicate); static Iterable<Node> getNodes(Node parent); static Iterable<Node> getNodes(Node parent, String nodeTypeName); static Iterable<Node> asIterable(NodeIterator iterator); static List<Node> asList(Iterable<Node> nodes); static String getName(Node content); static Iterable<Node> collectAllChildren(Node node); static Iterable<Node> collectAllChildren(Node node, Predicate predicate); static Iterable<Node> collectAllChildren(List<Node> nodes, Node parent, Predicate predicate); static Collection<Node> getAncestors(Node node); static String getNodeIdentifierIfPossible(Node content); static String getNodePathIfPossible(Node node); static String getPathIfPossible(Node node); static NodeIterator filterNodeType(NodeIterator iterator, String nodeType); static NodeIterator filterDuplicates(NodeIterator iterator); static NodeIterator filterParentNodeType(NodeIterator iterator, final String nodeType); static Collection<Node> getCollectionFromNodeIterator(NodeIterator iterator); static Collection<Node> getSortedCollectionFromNodeIterator(NodeIterator iterator); static void traceNodeProperties(Node nodeOp); static void traceNodeChildren(Node nodeOp); static AbstractPredicate<Property> ALL_PROPERTIES_EXCEPT_JCR_AND_MGNL_FILTER; static Predicate ALL_NODES_EXCEPT_JCR_FILTER; static AbstractPredicate<Node> EXCLUDE_META_DATA_FILTER; static AbstractPredicate<Node> MAGNOLIA_FILTER; }
@Test public void testAreSiblingsTrue() throws RepositoryException { Node subFirst1 = first.addNode("subFirst1"); Node subFirst2 = first.addNode("subFirst1"); boolean areSiblings = NodeUtil.isSameNameSiblings(subFirst1, subFirst2); assertEquals("Should be Siblings ", true, areSiblings); } @Test public void testAreSiblingsFalse() throws RepositoryException { Node subFirst1 = first.addNode("subFirst1"); Node subFirst2 = first.addNode("subFirst2"); boolean areSiblings = NodeUtil.isSameNameSiblings(subFirst1, subFirst2); assertEquals("Should not be Siblings ", false, areSiblings); }
NodeUtil { public static String combinePathAndName(String path, String name) { if ("/".equals(path)) { return "/" + name; } return path + "/" + name; } static Node getNodeByIdentifier(String workspace, String identifier); static boolean hasMixin(Node node, String mixinName); static boolean isNodeType(Node node, String type); static Node unwrap(Node node); static Node deepUnwrap(Node node, Class<? extends DelegateNodeWrapper> wrapper); static Node deepUnwrapAll(Node node, Class<? extends DelegateNodeWrapper> wrapperClass); static boolean isWrappedWith(Node node, Class<? extends DelegateNodeWrapper> wrapper); static void orderBefore(Node node, String siblingName); static void orderAfter(Node node, String siblingName); static void orderFirst(Node node); static void orderLast(Node node); static void orderNodeUp(Node node); static void orderNodeDown(Node node); static Node getSiblingBefore(Node node); static Node getSiblingAfter(Node node); static Iterable<Node> getSiblings(Node node); static Iterable<Node> getSiblings(Node node, String nodeTypeName); static Iterable<Node> getSiblings(Node node, Predicate predicate); static Iterable<Node> getSiblingsBefore(Node node); static Iterable<Node> getSiblingsAfter(Node node); static Iterable<Node> getSiblingsBefore(Node node, String nodeTypeName); static Iterable<Node> getSiblingsAfter(Node node, String nodeTypeName); static void moveNode(Node nodeToMove, Node newParent); static void moveNodeBefore(Node nodeToMove, Node target); static void moveNodeAfter(Node nodeToMove, Node target); static boolean isFirstSibling(Node node); static boolean isSameNameSiblings(Node node1, Node node2); static boolean isLastSibling(Node node); static void renameNode(Node node, String newName); static boolean isGranted(Node node, long permissions); static boolean isSame(Node lhs, Node rhs); static String combinePathAndName(String path, String name); static Node createPath(Node parent, String relPath, String primaryNodeTypeName); static Node createPath(Node parent, String relPath, String primaryNodeTypeName, boolean save); static void visit(Node node, NodeVisitor visitor); static void visit(Node node, NodeVisitor visitor, Predicate predicate); static Iterable<Node> getNodes(Node parent, Predicate predicate); static Iterable<Node> getNodes(Node parent); static Iterable<Node> getNodes(Node parent, String nodeTypeName); static Iterable<Node> asIterable(NodeIterator iterator); static List<Node> asList(Iterable<Node> nodes); static String getName(Node content); static Iterable<Node> collectAllChildren(Node node); static Iterable<Node> collectAllChildren(Node node, Predicate predicate); static Iterable<Node> collectAllChildren(List<Node> nodes, Node parent, Predicate predicate); static Collection<Node> getAncestors(Node node); static String getNodeIdentifierIfPossible(Node content); static String getNodePathIfPossible(Node node); static String getPathIfPossible(Node node); static NodeIterator filterNodeType(NodeIterator iterator, String nodeType); static NodeIterator filterDuplicates(NodeIterator iterator); static NodeIterator filterParentNodeType(NodeIterator iterator, final String nodeType); static Collection<Node> getCollectionFromNodeIterator(NodeIterator iterator); static Collection<Node> getSortedCollectionFromNodeIterator(NodeIterator iterator); static void traceNodeProperties(Node nodeOp); static void traceNodeChildren(Node nodeOp); static AbstractPredicate<Property> ALL_PROPERTIES_EXCEPT_JCR_AND_MGNL_FILTER; static Predicate ALL_NODES_EXCEPT_JCR_FILTER; static AbstractPredicate<Node> EXCLUDE_META_DATA_FILTER; static AbstractPredicate<Node> MAGNOLIA_FILTER; }
@Test public void testCombinePathAndName() throws RepositoryException { final String nodePath = "/someNode"; final String subNodeName = "subnode"; final String result = NodeUtil.combinePathAndName(nodePath, subNodeName); assertEquals(nodePath + "/" + subNodeName, result); } @Test public void testCombinePathAndNameForRootNode() throws RepositoryException { final String rootPath = "/"; final String subNodeName = "subnode"; final String result = NodeUtil.combinePathAndName(rootPath, subNodeName); assertEquals(rootPath + subNodeName, result); }
NodeUtil { public static Iterable<Node> getSiblings(Node node) throws RepositoryException { Node parent = node.getParent(); Iterable<Node> allSiblings = NodeUtil.getNodes(parent); List<Node> siblings = new ArrayList<Node>(); for(Node sibling: allSiblings) { if (!NodeUtil.isSame(node, sibling)) { siblings.add(sibling); } } return siblings; } static Node getNodeByIdentifier(String workspace, String identifier); static boolean hasMixin(Node node, String mixinName); static boolean isNodeType(Node node, String type); static Node unwrap(Node node); static Node deepUnwrap(Node node, Class<? extends DelegateNodeWrapper> wrapper); static Node deepUnwrapAll(Node node, Class<? extends DelegateNodeWrapper> wrapperClass); static boolean isWrappedWith(Node node, Class<? extends DelegateNodeWrapper> wrapper); static void orderBefore(Node node, String siblingName); static void orderAfter(Node node, String siblingName); static void orderFirst(Node node); static void orderLast(Node node); static void orderNodeUp(Node node); static void orderNodeDown(Node node); static Node getSiblingBefore(Node node); static Node getSiblingAfter(Node node); static Iterable<Node> getSiblings(Node node); static Iterable<Node> getSiblings(Node node, String nodeTypeName); static Iterable<Node> getSiblings(Node node, Predicate predicate); static Iterable<Node> getSiblingsBefore(Node node); static Iterable<Node> getSiblingsAfter(Node node); static Iterable<Node> getSiblingsBefore(Node node, String nodeTypeName); static Iterable<Node> getSiblingsAfter(Node node, String nodeTypeName); static void moveNode(Node nodeToMove, Node newParent); static void moveNodeBefore(Node nodeToMove, Node target); static void moveNodeAfter(Node nodeToMove, Node target); static boolean isFirstSibling(Node node); static boolean isSameNameSiblings(Node node1, Node node2); static boolean isLastSibling(Node node); static void renameNode(Node node, String newName); static boolean isGranted(Node node, long permissions); static boolean isSame(Node lhs, Node rhs); static String combinePathAndName(String path, String name); static Node createPath(Node parent, String relPath, String primaryNodeTypeName); static Node createPath(Node parent, String relPath, String primaryNodeTypeName, boolean save); static void visit(Node node, NodeVisitor visitor); static void visit(Node node, NodeVisitor visitor, Predicate predicate); static Iterable<Node> getNodes(Node parent, Predicate predicate); static Iterable<Node> getNodes(Node parent); static Iterable<Node> getNodes(Node parent, String nodeTypeName); static Iterable<Node> asIterable(NodeIterator iterator); static List<Node> asList(Iterable<Node> nodes); static String getName(Node content); static Iterable<Node> collectAllChildren(Node node); static Iterable<Node> collectAllChildren(Node node, Predicate predicate); static Iterable<Node> collectAllChildren(List<Node> nodes, Node parent, Predicate predicate); static Collection<Node> getAncestors(Node node); static String getNodeIdentifierIfPossible(Node content); static String getNodePathIfPossible(Node node); static String getPathIfPossible(Node node); static NodeIterator filterNodeType(NodeIterator iterator, String nodeType); static NodeIterator filterDuplicates(NodeIterator iterator); static NodeIterator filterParentNodeType(NodeIterator iterator, final String nodeType); static Collection<Node> getCollectionFromNodeIterator(NodeIterator iterator); static Collection<Node> getSortedCollectionFromNodeIterator(NodeIterator iterator); static void traceNodeProperties(Node nodeOp); static void traceNodeChildren(Node nodeOp); static AbstractPredicate<Property> ALL_PROPERTIES_EXCEPT_JCR_AND_MGNL_FILTER; static Predicate ALL_NODES_EXCEPT_JCR_FILTER; static AbstractPredicate<Node> EXCLUDE_META_DATA_FILTER; static AbstractPredicate<Node> MAGNOLIA_FILTER; }
@Test public void testGetSiblings() throws RepositoryException { Node subFirst0 = first.addNode("subFirst0", NodeTypes.Area.NAME); Node subFirst1 = first.addNode("subFirst1", NodeTypes.Component.NAME); Node subFirst2 = first.addNode("subFirst2", NodeTypes.Area.NAME); Node subFirst3 = first.addNode("subFirst3", NodeTypes.Component.NAME); Node subFirst4 = second.addNode("subSecond0"); Iterator<Node> iterator; iterator = NodeUtil.getSiblings(subFirst0).iterator(); assertEquals(subFirst1, iterator.next()); assertEquals(subFirst2, iterator.next()); assertEquals(subFirst3, iterator.next()); assertFalse(iterator.hasNext()); iterator = NodeUtil.getSiblings(subFirst1).iterator(); assertEquals(subFirst0, iterator.next()); assertEquals(subFirst2, iterator.next()); assertEquals(subFirst3, iterator.next()); assertFalse(iterator.hasNext()); iterator = NodeUtil.getSiblings(subFirst2).iterator(); assertEquals(subFirst0, iterator.next()); assertEquals(subFirst1, iterator.next()); assertEquals(subFirst3, iterator.next()); assertFalse(iterator.hasNext()); iterator = NodeUtil.getSiblings(subFirst3).iterator(); assertEquals(subFirst0, iterator.next()); assertEquals(subFirst1, iterator.next()); assertEquals(subFirst2, iterator.next()); assertFalse(iterator.hasNext()); iterator = NodeUtil.getSiblings(subFirst4).iterator(); assertFalse(iterator.hasNext()); } @Test public void testGetSiblingsWithType() throws RepositoryException { Node subFirst0 = first.addNode("subFirst0", NodeTypes.Area.NAME); Node subFirst1 = first.addNode("subFirst1", NodeTypes.Component.NAME); Node subFirst2 = first.addNode("subFirst2", NodeTypes.Area.NAME); Node subFirst3 = first.addNode("subFirst3", NodeTypes.Component.NAME); Node subSecond4 = second.addNode("subSecond0"); Iterator<Node> iterator; iterator = NodeUtil.getSiblings(subFirst0, NodeTypes.Component.NAME).iterator(); assertEquals(subFirst1, iterator.next()); assertEquals(subFirst3, iterator.next()); assertFalse(iterator.hasNext()); iterator = NodeUtil.getSiblings(subFirst1, NodeTypes.Area.NAME).iterator(); assertEquals(subFirst0, iterator.next()); assertEquals(subFirst2, iterator.next()); assertFalse(iterator.hasNext()); iterator = NodeUtil.getSiblings(subFirst2, NodeTypes.Area.NAME).iterator(); assertEquals(subFirst0, iterator.next()); assertFalse(iterator.hasNext()); iterator = NodeUtil.getSiblings(subFirst3, NodeTypes.Component.NAME).iterator(); assertEquals(subFirst1, iterator.next()); assertFalse(iterator.hasNext()); iterator = NodeUtil.getSiblings(subSecond4, NodeTypes.Component.NAME).iterator(); assertFalse(iterator.hasNext()); } @Test public void testGetSiblingsWithPredicate() throws RepositoryException { Node subFirst0 = first.addNode("subFirst0", NodeTypes.Area.NAME); Node subFirst1 = first.addNode("subFirst1", "someOtherNodeType"); Node subFirst2 = first.addNode("subFirst2", NodeTypes.Area.NAME); Node subFirst3 = first.addNode("subFirst3", NodeTypes.Component.NAME); Node subSecond4 = second.addNode("subSecond0"); Iterator<Node> iterator; iterator = NodeUtil.getSiblings(subFirst0, NodeUtil.EXCLUDE_META_DATA_FILTER).iterator(); assertEquals(subFirst1, iterator.next()); assertEquals(subFirst2, iterator.next()); assertEquals(subFirst3, iterator.next()); assertFalse(iterator.hasNext()); iterator = NodeUtil.getSiblings(subFirst1, NodeUtil.MAGNOLIA_FILTER).iterator(); assertEquals(subFirst0, iterator.next()); assertEquals(subFirst2, iterator.next()); assertEquals(subFirst3, iterator.next()); assertFalse(iterator.hasNext()); iterator = NodeUtil.getSiblings(subFirst2, NodeUtil.MAGNOLIA_FILTER).iterator(); assertEquals(subFirst0, iterator.next()); assertEquals(subFirst3, iterator.next()); assertFalse(iterator.hasNext()); iterator = NodeUtil.getSiblings(subFirst3, NodeUtil.ALL_NODES_EXCEPT_JCR_FILTER).iterator(); assertEquals(subFirst0, iterator.next()); assertEquals(subFirst1, iterator.next()); assertEquals(subFirst2, iterator.next()); assertFalse(iterator.hasNext()); iterator = NodeUtil.getSiblings(subSecond4, NodeUtil.MAGNOLIA_FILTER).iterator(); assertFalse(iterator.hasNext()); }
NodeUtil { public static Iterable<Node> getSiblingsBefore(Node node) throws RepositoryException { int toIndex = 0; Node parent = node.getParent(); List<Node> allSiblings = NodeUtil.asList(NodeUtil.getNodes(parent)); for(Node sibling: allSiblings) { if (NodeUtil.isSame(node, sibling)) { break; } toIndex++; } return allSiblings.subList(0, toIndex); } static Node getNodeByIdentifier(String workspace, String identifier); static boolean hasMixin(Node node, String mixinName); static boolean isNodeType(Node node, String type); static Node unwrap(Node node); static Node deepUnwrap(Node node, Class<? extends DelegateNodeWrapper> wrapper); static Node deepUnwrapAll(Node node, Class<? extends DelegateNodeWrapper> wrapperClass); static boolean isWrappedWith(Node node, Class<? extends DelegateNodeWrapper> wrapper); static void orderBefore(Node node, String siblingName); static void orderAfter(Node node, String siblingName); static void orderFirst(Node node); static void orderLast(Node node); static void orderNodeUp(Node node); static void orderNodeDown(Node node); static Node getSiblingBefore(Node node); static Node getSiblingAfter(Node node); static Iterable<Node> getSiblings(Node node); static Iterable<Node> getSiblings(Node node, String nodeTypeName); static Iterable<Node> getSiblings(Node node, Predicate predicate); static Iterable<Node> getSiblingsBefore(Node node); static Iterable<Node> getSiblingsAfter(Node node); static Iterable<Node> getSiblingsBefore(Node node, String nodeTypeName); static Iterable<Node> getSiblingsAfter(Node node, String nodeTypeName); static void moveNode(Node nodeToMove, Node newParent); static void moveNodeBefore(Node nodeToMove, Node target); static void moveNodeAfter(Node nodeToMove, Node target); static boolean isFirstSibling(Node node); static boolean isSameNameSiblings(Node node1, Node node2); static boolean isLastSibling(Node node); static void renameNode(Node node, String newName); static boolean isGranted(Node node, long permissions); static boolean isSame(Node lhs, Node rhs); static String combinePathAndName(String path, String name); static Node createPath(Node parent, String relPath, String primaryNodeTypeName); static Node createPath(Node parent, String relPath, String primaryNodeTypeName, boolean save); static void visit(Node node, NodeVisitor visitor); static void visit(Node node, NodeVisitor visitor, Predicate predicate); static Iterable<Node> getNodes(Node parent, Predicate predicate); static Iterable<Node> getNodes(Node parent); static Iterable<Node> getNodes(Node parent, String nodeTypeName); static Iterable<Node> asIterable(NodeIterator iterator); static List<Node> asList(Iterable<Node> nodes); static String getName(Node content); static Iterable<Node> collectAllChildren(Node node); static Iterable<Node> collectAllChildren(Node node, Predicate predicate); static Iterable<Node> collectAllChildren(List<Node> nodes, Node parent, Predicate predicate); static Collection<Node> getAncestors(Node node); static String getNodeIdentifierIfPossible(Node content); static String getNodePathIfPossible(Node node); static String getPathIfPossible(Node node); static NodeIterator filterNodeType(NodeIterator iterator, String nodeType); static NodeIterator filterDuplicates(NodeIterator iterator); static NodeIterator filterParentNodeType(NodeIterator iterator, final String nodeType); static Collection<Node> getCollectionFromNodeIterator(NodeIterator iterator); static Collection<Node> getSortedCollectionFromNodeIterator(NodeIterator iterator); static void traceNodeProperties(Node nodeOp); static void traceNodeChildren(Node nodeOp); static AbstractPredicate<Property> ALL_PROPERTIES_EXCEPT_JCR_AND_MGNL_FILTER; static Predicate ALL_NODES_EXCEPT_JCR_FILTER; static AbstractPredicate<Node> EXCLUDE_META_DATA_FILTER; static AbstractPredicate<Node> MAGNOLIA_FILTER; }
@Test public void testGetSiblingsBefore() throws RepositoryException { Node subFirst0 = first.addNode("subFirst0", NodeTypes.Area.NAME); Node subFirst1 = first.addNode("subFirst1", NodeTypes.Component.NAME); Node subFirst2 = first.addNode("subFirst2", NodeTypes.Area.NAME); Node subFirst3 = first.addNode("subFirst3", NodeTypes.Component.NAME); Node subFirst4 = second.addNode("subSecond0"); Iterator<Node> iterator; iterator = NodeUtil.getSiblingsBefore(subFirst0).iterator(); assertFalse(iterator.hasNext()); iterator = NodeUtil.getSiblingsBefore(subFirst1).iterator(); assertEquals(subFirst0, iterator.next()); assertFalse(iterator.hasNext()); iterator = NodeUtil.getSiblingsBefore(subFirst3).iterator(); assertEquals(subFirst0, iterator.next()); assertEquals(subFirst1, iterator.next()); assertEquals(subFirst2, iterator.next()); assertFalse(iterator.hasNext()); iterator = NodeUtil.getSiblingsBefore(subFirst4).iterator(); assertFalse(iterator.hasNext()); iterator = NodeUtil.getSiblingsBefore(subFirst2).iterator(); assertEquals(subFirst0, iterator.next()); assertEquals(subFirst1, iterator.next()); assertFalse(iterator.hasNext()); }
NodeUtil { public static Iterable<Node> getSiblingsAfter(Node node) throws RepositoryException { int fromIndex = 0; Node parent = node.getParent(); List<Node> allSiblings = NodeUtil.asList(NodeUtil.getNodes(parent)); for(Node sibling: allSiblings) { if (NodeUtil.isSame(node, sibling)) { fromIndex++; break; } fromIndex++; } return allSiblings.subList(fromIndex, allSiblings.size()); } static Node getNodeByIdentifier(String workspace, String identifier); static boolean hasMixin(Node node, String mixinName); static boolean isNodeType(Node node, String type); static Node unwrap(Node node); static Node deepUnwrap(Node node, Class<? extends DelegateNodeWrapper> wrapper); static Node deepUnwrapAll(Node node, Class<? extends DelegateNodeWrapper> wrapperClass); static boolean isWrappedWith(Node node, Class<? extends DelegateNodeWrapper> wrapper); static void orderBefore(Node node, String siblingName); static void orderAfter(Node node, String siblingName); static void orderFirst(Node node); static void orderLast(Node node); static void orderNodeUp(Node node); static void orderNodeDown(Node node); static Node getSiblingBefore(Node node); static Node getSiblingAfter(Node node); static Iterable<Node> getSiblings(Node node); static Iterable<Node> getSiblings(Node node, String nodeTypeName); static Iterable<Node> getSiblings(Node node, Predicate predicate); static Iterable<Node> getSiblingsBefore(Node node); static Iterable<Node> getSiblingsAfter(Node node); static Iterable<Node> getSiblingsBefore(Node node, String nodeTypeName); static Iterable<Node> getSiblingsAfter(Node node, String nodeTypeName); static void moveNode(Node nodeToMove, Node newParent); static void moveNodeBefore(Node nodeToMove, Node target); static void moveNodeAfter(Node nodeToMove, Node target); static boolean isFirstSibling(Node node); static boolean isSameNameSiblings(Node node1, Node node2); static boolean isLastSibling(Node node); static void renameNode(Node node, String newName); static boolean isGranted(Node node, long permissions); static boolean isSame(Node lhs, Node rhs); static String combinePathAndName(String path, String name); static Node createPath(Node parent, String relPath, String primaryNodeTypeName); static Node createPath(Node parent, String relPath, String primaryNodeTypeName, boolean save); static void visit(Node node, NodeVisitor visitor); static void visit(Node node, NodeVisitor visitor, Predicate predicate); static Iterable<Node> getNodes(Node parent, Predicate predicate); static Iterable<Node> getNodes(Node parent); static Iterable<Node> getNodes(Node parent, String nodeTypeName); static Iterable<Node> asIterable(NodeIterator iterator); static List<Node> asList(Iterable<Node> nodes); static String getName(Node content); static Iterable<Node> collectAllChildren(Node node); static Iterable<Node> collectAllChildren(Node node, Predicate predicate); static Iterable<Node> collectAllChildren(List<Node> nodes, Node parent, Predicate predicate); static Collection<Node> getAncestors(Node node); static String getNodeIdentifierIfPossible(Node content); static String getNodePathIfPossible(Node node); static String getPathIfPossible(Node node); static NodeIterator filterNodeType(NodeIterator iterator, String nodeType); static NodeIterator filterDuplicates(NodeIterator iterator); static NodeIterator filterParentNodeType(NodeIterator iterator, final String nodeType); static Collection<Node> getCollectionFromNodeIterator(NodeIterator iterator); static Collection<Node> getSortedCollectionFromNodeIterator(NodeIterator iterator); static void traceNodeProperties(Node nodeOp); static void traceNodeChildren(Node nodeOp); static AbstractPredicate<Property> ALL_PROPERTIES_EXCEPT_JCR_AND_MGNL_FILTER; static Predicate ALL_NODES_EXCEPT_JCR_FILTER; static AbstractPredicate<Node> EXCLUDE_META_DATA_FILTER; static AbstractPredicate<Node> MAGNOLIA_FILTER; }
@Test public void testGetSiblingsAfter() throws RepositoryException { Node subFirst0 = first.addNode("subFirst0", NodeTypes.Area.NAME); Node subFirst1 = first.addNode("subFirst1", NodeTypes.Component.NAME); Node subFirst2 = first.addNode("subFirst2", NodeTypes.Area.NAME); Node subFirst3 = first.addNode("subFirst3", NodeTypes.Component.NAME); Node subFirst4 = second.addNode("subSecond0"); Iterator<Node> iterator; iterator = NodeUtil.getSiblingsAfter(subFirst0).iterator(); assertEquals(subFirst1, iterator.next()); assertEquals(subFirst2, iterator.next()); assertEquals(subFirst3, iterator.next()); assertFalse(iterator.hasNext()); iterator = NodeUtil.getSiblingsAfter(subFirst2).iterator(); assertEquals(subFirst3, iterator.next()); iterator = NodeUtil.getSiblingsAfter(subFirst3).iterator(); assertFalse(iterator.hasNext()); iterator = NodeUtil.getSiblingsAfter(subFirst4).iterator(); assertFalse(iterator.hasNext()); iterator = NodeUtil.getSiblingsAfter(subFirst1).iterator(); assertEquals(subFirst2, iterator.next()); assertEquals(subFirst3, iterator.next()); assertFalse(iterator.hasNext()); } @Test public void testGetSiblingsAfterWithType() throws RepositoryException { Node subFirst1 = first.addNode("subFirst1", NodeTypes.Area.NAME); Node subFirst2 = first.addNode("subFirst2", NodeTypes.Component.NAME); Node subFirst3 = first.addNode("subFirst3", NodeTypes.Component.NAME); Node subFirst4 = second.addNode("subSecond0"); Iterator<Node> iterator; iterator = NodeUtil.getSiblingsAfter(subFirst1, NodeTypes.Area.NAME).iterator(); assertFalse(iterator.hasNext()); iterator = NodeUtil.getSiblingsAfter(subFirst1, NodeTypes.Component.NAME).iterator(); assertEquals(subFirst2, iterator.next()); assertEquals(subFirst3, iterator.next()); assertFalse(iterator.hasNext()); iterator = NodeUtil.getSiblingsAfter(subFirst2, NodeTypes.Component.NAME).iterator(); assertEquals(subFirst3, iterator.next()); iterator = NodeUtil.getSiblingsAfter(subFirst4, NodeTypes.Area.NAME).iterator(); assertFalse(iterator.hasNext()); }
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); }
@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)); }
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); }
@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)); }
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(); }
@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()); }
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(); }
@Test public void testAddNodeWithString() throws RepositoryException { final NodeOperation op = Ops.addNode(CHILD_NAME); op.exec(rootNode, eh); assertTrue(rootNode.hasNode(CHILD_NAME)); }
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(); }
@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()); }
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(); }
@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"); }
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(); }
@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)); }
ExtendingNodeWrapper extends ChildWrappingNodeWrapper { @Override public Node getNode(String relPath) throws PathNotFoundException, RepositoryException { if (getWrappedNode().hasNode(relPath)) { return wrapNode(getWrappedNode().getNode(relPath)); } else if (extending && extendedNode.hasNode(relPath)) { return(extendedNode.getNode(relPath)); } else { throw new PathNotFoundException("Node does not exists: [" + relPath + "]"); } } ExtendingNodeWrapper(Node wrappedNode); ExtendingNodeWrapper(Node wrappedNode, boolean failOnError); protected ExtendingNodeWrapper(Node wrappedNode, Node extendedNode); @Override boolean hasNode(String relPath); @Override Node getNode(String relPath); @Override NodeIterator getNodes(); @Override NodeIterator getNodes(String[] nameGlobs); @Override NodeIterator getNodes(String namePattern); @Override boolean hasProperty(String relPath); @Override Property getProperty(String relPath); @Override PropertyIterator getProperties(); @Override PropertyIterator getProperties(String[] nameGlobs); @Override PropertyIterator getProperties(String namePattern); @Override Node wrapNode(Node node); @Override Node getWrappedNode(); @Override void setWrappedNode(Node node); boolean isExtending(); }
@Test public void testExtendsNonAbsolutelyAndNodeIsNotExisting() throws IOException, RepositoryException { session = SessionTestUtil.createSession("test", "/superbase.nodeData1=org1\n" + "/superbase/uglyChild.nodeDataX=over1\n" + "/impl/node.extends=/superbase\n" + "/impl/node2.extends=../../superbase/uglyChild\n" + "/impl/node3.extends=../../superbase/wrongNode" ); try { Node plainNode = session.getNode("/impl/node3"); new ExtendingNodeWrapper(plainNode, true); fail("Must never get here!"); } catch (RuntimeException e) { assertEquals("Can't find referenced node for value: MockNode [primaryType=mgnl:contentNode, name=node3]", e.getMessage()); } } @Test public void testExtendsAbsolutelyAndNodeIsNotExisting() throws IOException, RepositoryException { session = SessionTestUtil.createSession("test", "/impl/node.extends=/base/node\n" + "/impl/node.nodeData2=org2" ); Node plainNode = session.getNode("/impl/node"); try { new ExtendingNodeWrapper(plainNode, true); fail("should never get here..."); } catch (RuntimeException e) { assertEquals("Can't find referenced node for value: MockNode [primaryType=mgnl:contentNode, name=node]", e.getMessage()); } }
DelegateSessionWrapper implements Session { public Session unwrap() { Session session = getWrappedSession(); if (session instanceof DelegateSessionWrapper) { session = ((DelegateSessionWrapper) session).unwrap(); } return session; } protected DelegateSessionWrapper(Session wrapped); Session getWrappedSession(); void setWrappedSession(Session session); @Override String toString(); @Override void addLockToken(String lt); @Override void checkPermission(String absPath, String actions); @Override void exportDocumentView(String absPath, ContentHandler contentHandler, boolean skipBinary, boolean noRecurse); @Override void exportDocumentView(String absPath, OutputStream out, boolean skipBinary, boolean noRecurse); @Override void exportSystemView(String absPath, ContentHandler contentHandler, boolean skipBinary, boolean noRecurse); @Override void exportSystemView(String absPath, OutputStream out, boolean skipBinary, boolean noRecurse); @Override AccessControlManager getAccessControlManager(); @Override Object getAttribute(String name); @Override String[] getAttributeNames(); @Override ContentHandler getImportContentHandler(String parentAbsPath, int uuidBehavior); @Override Item getItem(String absPath); @Override String[] getLockTokens(); @Override String getNamespacePrefix(String uri); @Override String[] getNamespacePrefixes(); @Override String getNamespaceURI(String prefix); @Override Node getNode(String absPath); @Override Node getNodeByIdentifier(String id); @Override Node getNodeByUUID(String uuid); @Override Property getProperty(String absPath); @Override Repository getRepository(); @Override RetentionManager getRetentionManager(); @Override Node getRootNode(); @Override String getUserID(); @Override ValueFactory getValueFactory(); @Override Workspace getWorkspace(); @Override boolean hasCapability(String methodName, Object target, Object[] arguments); @Override boolean hasPendingChanges(); @Override boolean hasPermission(String absPath, String actions); @Override Session impersonate(Credentials credentials); @Override void importXML(String parentAbsPath, InputStream in, int uuidBehavior); @Override boolean isLive(); @Override boolean itemExists(String absPath); @Override void logout(); @Override void move(String srcAbsPath, String destAbsPath); @Override boolean nodeExists(String absPath); @Override boolean propertyExists(String absPath); @Override void refresh(boolean keepChanges); @Override void removeItem(String absPath); @Override void removeLockToken(String lt); @Override void save(); @Override void setNamespacePrefix(String prefix, String uri); Session unwrap(); }
@Test public void testUnwrap() { final Session jcrSession = new MockSession("test"); final DelegateSessionWrapper wrapperTwo = new MgnlVersioningSession(jcrSession); Session result = wrapperTwo.unwrap(); assertEquals(jcrSession, result); }
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); }
@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()); }
I18nNodeWrapper extends ContentDecoratorNodeWrapper { @Override public boolean hasProperty(String relPath) throws RepositoryException { return i18nSupport.hasProperty(getWrappedNode(), relPath); } I18nNodeWrapper(Node wrapped); @Override boolean hasProperty(String relPath); @Override Property getProperty(String relPath); }
@Test public void testGetPropertyDoesntReturnResourceNode() throws Exception { final MockNode node = new MockNode("boo"); final I18nNodeWrapper wrappedNode = new I18nNodeWrapper(node); assertFalse(wrappedNode.hasProperty("blah")); node.addNode("blah", "mgnl:resource"); assertFalse(wrappedNode.hasProperty("blah")); } @Test public void testHasPropertyReturnsTrueWhenOnlyLocaleVariantIsAvailable() throws Exception { final I18nContentSupport defSupport = Components.getComponent(I18nContentSupport.class); defSupport.setLocale(new Locale("de")); final MockNode node = new MockNode("boo"); final I18nNodeWrapper wrappedNode = new I18nNodeWrapper(node); node.setProperty("foo_de", "deutsches Foo"); boolean propertyExists = wrappedNode.hasProperty("foo"); assertTrue(propertyExists); } @Test public void testHasPropertyReturnsTrueWhenOnlyDefaultIsAvailable() throws Exception { final I18nContentSupport defSupport = Components.getComponent(I18nContentSupport.class); defSupport.setLocale(new Locale("de")); final MockNode node = new MockNode("boo"); final I18nNodeWrapper wrappedNode = new I18nNodeWrapper(node); node.setProperty("foo", "english foo"); boolean propertyExists = wrappedNode.hasProperty("foo"); assertTrue(propertyExists); } @Test public void testHasPropertyReturnsFalseWhenNoSuchPropertyExists() throws Exception { final I18nContentSupport defSupport = Components.getComponent(I18nContentSupport.class); defSupport.setLocale(new Locale("de")); final MockNode node = new MockNode("boo"); final I18nNodeWrapper wrappedNode = new I18nNodeWrapper(node); boolean propertyExists = wrappedNode.hasProperty("foo"); assertFalse(propertyExists); }
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(); }
@Test public void testNodeNameIsWrappedAndEncoded() throws Exception { MockNode node = new MockNode("<html>"); HTMLEscapingNodeWrapper wrapper = new HTMLEscapingNodeWrapper(node, false); String name = wrapper.getName(); assertEquals("&lt;html&gt;", name); } @Test public void testPropertyNameIsWrappedAndEncoded() throws Exception { MockNode node = new MockNode(); node.setProperty("<html>", "bla"); HTMLEscapingNodeWrapper wrapper = new HTMLEscapingNodeWrapper(node, false); assertEquals("&lt;html&gt;", 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("&lt;&gt;&quot;&amp;", name); }