method2testcases
stringlengths 118
3.08k
|
---|
### Question:
ContentRepository { public static Provider getRepositoryProvider(String repositoryOrLogicalWorkspace) { RepositoryManager repositoryManager = Components.getComponent(RepositoryManager.class); if (!repositoryManager.hasRepository(repositoryOrLogicalWorkspace)) { repositoryOrLogicalWorkspace = getMappedRepositoryName(repositoryOrLogicalWorkspace); } return repositoryManager.getRepositoryProvider(repositoryOrLogicalWorkspace); } private ContentRepository(); static void init(); static void shutdown(); static boolean checkIfInitialized(); static boolean checkIfInitialized(String logicalWorkspaceName); static void reload(); static void loadRepository(RepositoryDefinition repositoryDefinition); static void loadWorkspace(String repositoryId, String workspaceName); static String getParentRepositoryName(String physicalWorkspaceName); static String getMappedRepositoryName(String logicalWorkspaceName); static String getMappedWorkspaceName(String logicalWorkspaceName); static void addMappedRepositoryName(String logicalWorkspaceName, String repositoryName); static void addMappedRepositoryName(String logicalWorkspaceName, String repositoryName, String workspaceName); static String getDefaultWorkspace(String repositoryId); static Repository getRepository(String repositoryOrLogicalWorkspace); static Provider getRepositoryProvider(String repositoryOrLogicalWorkspace); static RepositoryDefinition getRepositoryMapping(String repositoryOrLogicalWorkspace); static boolean hasRepositoryMapping(String repositoryOrLogicalWorkspace); static Iterator<String> getAllRepositoryNames(); static String getInternalWorkspaceName(String physicalWorkspaceName); static final String WEBSITE; static final String USERS; static final String USER_ROLES; static final String USER_GROUPS; static final String CONFIG; static final String VERSION_STORE; static final String NAMESPACE_PREFIX; static final String NAMESPACE_URI; static final String DEFAULT_WORKSPACE; static String REPOSITORY_USER; static String REPOSITORY_PSWD; }### Answer:
@Test @Ignore public void testUnknownRepositoryShouldAlsoYieldMeaningfulExceptionMessageForRepositoryProviders() { try { ContentRepository.getRepositoryProvider("dummy"); fail("should have failed, since we haven't set any repository at all"); } catch (Throwable t) { assertEquals("Failed to retrieve repository provider 'dummy' (mapped as 'dummy'). Your Magnolia instance might not have been initialized properly.", t.getMessage()); } } |
### Question:
AggregationState { protected String stripContextPathIfExists(String uri) { String contextPath = MgnlContext.getContextPath(); if (uri != null && uri.startsWith(contextPath + "/")) { return StringUtils.removeStart(uri, contextPath); } return uri; } void setOriginalURI(String originalURI); void setOriginalBrowserURI(String originalBrowserURI); void setCurrentURI(String currentURI); void setQueryString(String queryString); String getQueryString(); String getCurrentURI(); String getCharacterEncoding(); String getOriginalURI(); String getOriginalURL(); void setOriginalURL(String originalURL); String getOriginalBrowserURI(); String getOriginalBrowserURL(); void setOriginalBrowserURL(String originalBrowserURL); void setCharacterEncoding(String characterEncoding); String getExtension(); void setExtension(String extension); File getFile(); void setFile(File file); String getHandle(); void setHandle(String handle); Content getMainContent(); void setMainContent(Content mainContent); Content getCurrentContent(); void setCurrentContent(Content currentContent); String getRepository(); void setRepository(String repository); String getSelector(); void setSelector(String selector); String getTemplateName(); void setTemplateName(String templateName); Locale getLocale(); void setLocale(Locale locale); boolean isPreviewMode(); void setPreviewMode(boolean previewMode); Channel getChannel(); void setChannel(Channel channel); void resetURIs(); String[] getSelectors(); }### Answer:
@Test public void testUriDecodingShouldStripCtxPath() { assertEquals("/pouet", aggState.stripContextPathIfExists("/foo/pouet")); }
@Test public void testUriDecodingShouldReturnPassedURIDoesntContainCtxPath() { assertEquals("/pouet", aggState.stripContextPathIfExists("/pouet")); } |
### Question:
MetaData { public String getTitle() { return getStringProperty(TITLE); } protected MetaData(Node workingNode, AccessManager ignoredAccessManager); MetaData(Node workingNode); String getTitle(); void setTitle(String value); void setCreationDate(); Calendar getCreationDate(); void setActivated(); void setUnActivated(); boolean getIsActivated(); int getActivationStatus(); void setLastActivationActionDate(); Calendar getLastActionDate(); void setModificationDate(); Calendar getModificationDate(); String getAuthorId(); void setAuthorId(String value); String getActivatorId(); void setActivatorId(String value); String getTemplate(); void setTemplate(String value); void setProperty(String name, String value); void setProperty(String name, long value); void setProperty(String name, double value); void setProperty(String name, boolean value); void setProperty(String name, Calendar value); boolean getBooleanProperty(String name); double getDoubleProperty(String name); long getLongProperty(String name); String getStringProperty(String name); Calendar getDateProperty(String name); void removeProperty(String name); static final String TITLE; static final String CREATION_DATE; static final String LAST_MODIFIED; static final String LAST_ACTION; static final String AUTHOR_ID; static final String ACTIVATOR_ID; static final String TEMPLATE; static final String TEMPLATE_TYPE; static final String ACTIVATED; static final String DEFAULT_META_NODE; static final int ACTIVATION_STATUS_NOT_ACTIVATED; static final int ACTIVATION_STATUS_MODIFIED; static final int ACTIVATION_STATUS_ACTIVATED; }### Answer:
@Test(expected = IllegalArgumentException.class) public void testGetTitleThrowsException() { new MetaData(root).getTitle(); } |
### Question:
MetaData { public void setTitle(String value) { setProperty(TITLE, value); } protected MetaData(Node workingNode, AccessManager ignoredAccessManager); MetaData(Node workingNode); String getTitle(); void setTitle(String value); void setCreationDate(); Calendar getCreationDate(); void setActivated(); void setUnActivated(); boolean getIsActivated(); int getActivationStatus(); void setLastActivationActionDate(); Calendar getLastActionDate(); void setModificationDate(); Calendar getModificationDate(); String getAuthorId(); void setAuthorId(String value); String getActivatorId(); void setActivatorId(String value); String getTemplate(); void setTemplate(String value); void setProperty(String name, String value); void setProperty(String name, long value); void setProperty(String name, double value); void setProperty(String name, boolean value); void setProperty(String name, Calendar value); boolean getBooleanProperty(String name); double getDoubleProperty(String name); long getLongProperty(String name); String getStringProperty(String name); Calendar getDateProperty(String name); void removeProperty(String name); static final String TITLE; static final String CREATION_DATE; static final String LAST_MODIFIED; static final String LAST_ACTION; static final String AUTHOR_ID; static final String ACTIVATOR_ID; static final String TEMPLATE; static final String TEMPLATE_TYPE; static final String ACTIVATED; static final String DEFAULT_META_NODE; static final int ACTIVATION_STATUS_NOT_ACTIVATED; static final int ACTIVATION_STATUS_MODIFIED; static final int ACTIVATION_STATUS_ACTIVATED; }### Answer:
@Test(expected = IllegalArgumentException.class) public void testSetTitleThrowsException() { new MetaData(root).setTitle("Title"); } |
### Question:
MetaData { public void setCreationDate() { Calendar value = new GregorianCalendar(TimeZone.getDefault()); setProperty(CREATION_DATE, value); } protected MetaData(Node workingNode, AccessManager ignoredAccessManager); MetaData(Node workingNode); String getTitle(); void setTitle(String value); void setCreationDate(); Calendar getCreationDate(); void setActivated(); void setUnActivated(); boolean getIsActivated(); int getActivationStatus(); void setLastActivationActionDate(); Calendar getLastActionDate(); void setModificationDate(); Calendar getModificationDate(); String getAuthorId(); void setAuthorId(String value); String getActivatorId(); void setActivatorId(String value); String getTemplate(); void setTemplate(String value); void setProperty(String name, String value); void setProperty(String name, long value); void setProperty(String name, double value); void setProperty(String name, boolean value); void setProperty(String name, Calendar value); boolean getBooleanProperty(String name); double getDoubleProperty(String name); long getLongProperty(String name); String getStringProperty(String name); Calendar getDateProperty(String name); void removeProperty(String name); static final String TITLE; static final String CREATION_DATE; static final String LAST_MODIFIED; static final String LAST_ACTION; static final String AUTHOR_ID; static final String ACTIVATOR_ID; static final String TEMPLATE; static final String TEMPLATE_TYPE; static final String ACTIVATED; static final String DEFAULT_META_NODE; static final int ACTIVATION_STATUS_NOT_ACTIVATED; static final int ACTIVATION_STATUS_MODIFIED; static final int ACTIVATION_STATUS_ACTIVATED; }### Answer:
@Test public void testSetCreationDate() throws RepositoryException { new MetaData(root).setCreationDate(); assertTrue(root.hasProperty(NodeTypes.Created.CREATED)); } |
### Question:
MetaData { public Calendar getCreationDate() { return this.getDateProperty(CREATION_DATE); } protected MetaData(Node workingNode, AccessManager ignoredAccessManager); MetaData(Node workingNode); String getTitle(); void setTitle(String value); void setCreationDate(); Calendar getCreationDate(); void setActivated(); void setUnActivated(); boolean getIsActivated(); int getActivationStatus(); void setLastActivationActionDate(); Calendar getLastActionDate(); void setModificationDate(); Calendar getModificationDate(); String getAuthorId(); void setAuthorId(String value); String getActivatorId(); void setActivatorId(String value); String getTemplate(); void setTemplate(String value); void setProperty(String name, String value); void setProperty(String name, long value); void setProperty(String name, double value); void setProperty(String name, boolean value); void setProperty(String name, Calendar value); boolean getBooleanProperty(String name); double getDoubleProperty(String name); long getLongProperty(String name); String getStringProperty(String name); Calendar getDateProperty(String name); void removeProperty(String name); static final String TITLE; static final String CREATION_DATE; static final String LAST_MODIFIED; static final String LAST_ACTION; static final String AUTHOR_ID; static final String ACTIVATOR_ID; static final String TEMPLATE; static final String TEMPLATE_TYPE; static final String ACTIVATED; static final String DEFAULT_META_NODE; static final int ACTIVATION_STATUS_NOT_ACTIVATED; static final int ACTIVATION_STATUS_MODIFIED; static final int ACTIVATION_STATUS_ACTIVATED; }### Answer:
@Test public void testGetCreationDate() throws RepositoryException { Calendar expected = Calendar.getInstance(); root.setProperty(NodeTypes.Created.CREATED, expected); Calendar actual = new MetaData(root).getCreationDate(); assertEquals(expected.getTimeInMillis(), actual.getTimeInMillis()); } |
### Question:
MetaData { public void setActivated() { setProperty(ACTIVATED, true); } protected MetaData(Node workingNode, AccessManager ignoredAccessManager); MetaData(Node workingNode); String getTitle(); void setTitle(String value); void setCreationDate(); Calendar getCreationDate(); void setActivated(); void setUnActivated(); boolean getIsActivated(); int getActivationStatus(); void setLastActivationActionDate(); Calendar getLastActionDate(); void setModificationDate(); Calendar getModificationDate(); String getAuthorId(); void setAuthorId(String value); String getActivatorId(); void setActivatorId(String value); String getTemplate(); void setTemplate(String value); void setProperty(String name, String value); void setProperty(String name, long value); void setProperty(String name, double value); void setProperty(String name, boolean value); void setProperty(String name, Calendar value); boolean getBooleanProperty(String name); double getDoubleProperty(String name); long getLongProperty(String name); String getStringProperty(String name); Calendar getDateProperty(String name); void removeProperty(String name); static final String TITLE; static final String CREATION_DATE; static final String LAST_MODIFIED; static final String LAST_ACTION; static final String AUTHOR_ID; static final String ACTIVATOR_ID; static final String TEMPLATE; static final String TEMPLATE_TYPE; static final String ACTIVATED; static final String DEFAULT_META_NODE; static final int ACTIVATION_STATUS_NOT_ACTIVATED; static final int ACTIVATION_STATUS_MODIFIED; static final int ACTIVATION_STATUS_ACTIVATED; }### Answer:
@Test public void testSetActivated() throws RepositoryException { new MetaData(root).setActivated(); assertTrue(root.getProperty(NodeTypes.Activatable.ACTIVATION_STATUS).getBoolean()); } |
### Question:
MetaData { public void setUnActivated() { setProperty(ACTIVATED, false); } protected MetaData(Node workingNode, AccessManager ignoredAccessManager); MetaData(Node workingNode); String getTitle(); void setTitle(String value); void setCreationDate(); Calendar getCreationDate(); void setActivated(); void setUnActivated(); boolean getIsActivated(); int getActivationStatus(); void setLastActivationActionDate(); Calendar getLastActionDate(); void setModificationDate(); Calendar getModificationDate(); String getAuthorId(); void setAuthorId(String value); String getActivatorId(); void setActivatorId(String value); String getTemplate(); void setTemplate(String value); void setProperty(String name, String value); void setProperty(String name, long value); void setProperty(String name, double value); void setProperty(String name, boolean value); void setProperty(String name, Calendar value); boolean getBooleanProperty(String name); double getDoubleProperty(String name); long getLongProperty(String name); String getStringProperty(String name); Calendar getDateProperty(String name); void removeProperty(String name); static final String TITLE; static final String CREATION_DATE; static final String LAST_MODIFIED; static final String LAST_ACTION; static final String AUTHOR_ID; static final String ACTIVATOR_ID; static final String TEMPLATE; static final String TEMPLATE_TYPE; static final String ACTIVATED; static final String DEFAULT_META_NODE; static final int ACTIVATION_STATUS_NOT_ACTIVATED; static final int ACTIVATION_STATUS_MODIFIED; static final int ACTIVATION_STATUS_ACTIVATED; }### Answer:
@Test public void testSetUnActivated() throws RepositoryException { root.setProperty(NodeTypes.Activatable.ACTIVATION_STATUS, true); new MetaData(root).setUnActivated(); assertFalse(root.getProperty(NodeTypes.Activatable.ACTIVATION_STATUS).getBoolean()); } |
### Question:
MetaData { public boolean getIsActivated() { return getBooleanProperty(ACTIVATED); } protected MetaData(Node workingNode, AccessManager ignoredAccessManager); MetaData(Node workingNode); String getTitle(); void setTitle(String value); void setCreationDate(); Calendar getCreationDate(); void setActivated(); void setUnActivated(); boolean getIsActivated(); int getActivationStatus(); void setLastActivationActionDate(); Calendar getLastActionDate(); void setModificationDate(); Calendar getModificationDate(); String getAuthorId(); void setAuthorId(String value); String getActivatorId(); void setActivatorId(String value); String getTemplate(); void setTemplate(String value); void setProperty(String name, String value); void setProperty(String name, long value); void setProperty(String name, double value); void setProperty(String name, boolean value); void setProperty(String name, Calendar value); boolean getBooleanProperty(String name); double getDoubleProperty(String name); long getLongProperty(String name); String getStringProperty(String name); Calendar getDateProperty(String name); void removeProperty(String name); static final String TITLE; static final String CREATION_DATE; static final String LAST_MODIFIED; static final String LAST_ACTION; static final String AUTHOR_ID; static final String ACTIVATOR_ID; static final String TEMPLATE; static final String TEMPLATE_TYPE; static final String ACTIVATED; static final String DEFAULT_META_NODE; static final int ACTIVATION_STATUS_NOT_ACTIVATED; static final int ACTIVATION_STATUS_MODIFIED; static final int ACTIVATION_STATUS_ACTIVATED; }### Answer:
@Test public void testGetIsActivated() throws RepositoryException { assertFalse(new MetaData(root).getIsActivated()); root.setProperty(NodeTypes.Activatable.ACTIVATION_STATUS, true); assertTrue(new MetaData(root).getIsActivated()); } |
### Question:
MetaData { public int getActivationStatus() { if (getIsActivated()) { if (getModificationDate() != null && getModificationDate().after(getLastActionDate())) { return ACTIVATION_STATUS_MODIFIED; } return ACTIVATION_STATUS_ACTIVATED; } return ACTIVATION_STATUS_NOT_ACTIVATED; } protected MetaData(Node workingNode, AccessManager ignoredAccessManager); MetaData(Node workingNode); String getTitle(); void setTitle(String value); void setCreationDate(); Calendar getCreationDate(); void setActivated(); void setUnActivated(); boolean getIsActivated(); int getActivationStatus(); void setLastActivationActionDate(); Calendar getLastActionDate(); void setModificationDate(); Calendar getModificationDate(); String getAuthorId(); void setAuthorId(String value); String getActivatorId(); void setActivatorId(String value); String getTemplate(); void setTemplate(String value); void setProperty(String name, String value); void setProperty(String name, long value); void setProperty(String name, double value); void setProperty(String name, boolean value); void setProperty(String name, Calendar value); boolean getBooleanProperty(String name); double getDoubleProperty(String name); long getLongProperty(String name); String getStringProperty(String name); Calendar getDateProperty(String name); void removeProperty(String name); static final String TITLE; static final String CREATION_DATE; static final String LAST_MODIFIED; static final String LAST_ACTION; static final String AUTHOR_ID; static final String ACTIVATOR_ID; static final String TEMPLATE; static final String TEMPLATE_TYPE; static final String ACTIVATED; static final String DEFAULT_META_NODE; static final int ACTIVATION_STATUS_NOT_ACTIVATED; static final int ACTIVATION_STATUS_MODIFIED; static final int ACTIVATION_STATUS_ACTIVATED; }### Answer:
@Test public void testGetActivationStatusReturnsNotActivatedWhenNotActivated() { assertEquals(NodeTypes.Activatable.ACTIVATION_STATUS_NOT_ACTIVATED, new MetaData(root).getActivationStatus()); } |
### Question:
MetaData { public void setLastActivationActionDate() { Calendar value = new GregorianCalendar(TimeZone.getDefault()); setProperty(LAST_ACTION, value); } protected MetaData(Node workingNode, AccessManager ignoredAccessManager); MetaData(Node workingNode); String getTitle(); void setTitle(String value); void setCreationDate(); Calendar getCreationDate(); void setActivated(); void setUnActivated(); boolean getIsActivated(); int getActivationStatus(); void setLastActivationActionDate(); Calendar getLastActionDate(); void setModificationDate(); Calendar getModificationDate(); String getAuthorId(); void setAuthorId(String value); String getActivatorId(); void setActivatorId(String value); String getTemplate(); void setTemplate(String value); void setProperty(String name, String value); void setProperty(String name, long value); void setProperty(String name, double value); void setProperty(String name, boolean value); void setProperty(String name, Calendar value); boolean getBooleanProperty(String name); double getDoubleProperty(String name); long getLongProperty(String name); String getStringProperty(String name); Calendar getDateProperty(String name); void removeProperty(String name); static final String TITLE; static final String CREATION_DATE; static final String LAST_MODIFIED; static final String LAST_ACTION; static final String AUTHOR_ID; static final String ACTIVATOR_ID; static final String TEMPLATE; static final String TEMPLATE_TYPE; static final String ACTIVATED; static final String DEFAULT_META_NODE; static final int ACTIVATION_STATUS_NOT_ACTIVATED; static final int ACTIVATION_STATUS_MODIFIED; static final int ACTIVATION_STATUS_ACTIVATED; }### Answer:
@Test public void testSetLastActivationActionDate() throws RepositoryException { assertFalse(root.hasProperty(NodeTypes.Activatable.LAST_ACTIVATED)); new MetaData(root).setLastActivationActionDate(); assertTrue(root.hasProperty(NodeTypes.Activatable.LAST_ACTIVATED)); } |
### Question:
MetaData { public Calendar getLastActionDate() { return getDateProperty(LAST_ACTION); } protected MetaData(Node workingNode, AccessManager ignoredAccessManager); MetaData(Node workingNode); String getTitle(); void setTitle(String value); void setCreationDate(); Calendar getCreationDate(); void setActivated(); void setUnActivated(); boolean getIsActivated(); int getActivationStatus(); void setLastActivationActionDate(); Calendar getLastActionDate(); void setModificationDate(); Calendar getModificationDate(); String getAuthorId(); void setAuthorId(String value); String getActivatorId(); void setActivatorId(String value); String getTemplate(); void setTemplate(String value); void setProperty(String name, String value); void setProperty(String name, long value); void setProperty(String name, double value); void setProperty(String name, boolean value); void setProperty(String name, Calendar value); boolean getBooleanProperty(String name); double getDoubleProperty(String name); long getLongProperty(String name); String getStringProperty(String name); Calendar getDateProperty(String name); void removeProperty(String name); static final String TITLE; static final String CREATION_DATE; static final String LAST_MODIFIED; static final String LAST_ACTION; static final String AUTHOR_ID; static final String ACTIVATOR_ID; static final String TEMPLATE; static final String TEMPLATE_TYPE; static final String ACTIVATED; static final String DEFAULT_META_NODE; static final int ACTIVATION_STATUS_NOT_ACTIVATED; static final int ACTIVATION_STATUS_MODIFIED; static final int ACTIVATION_STATUS_ACTIVATED; }### Answer:
@Test public void testGetLastActionDate() throws RepositoryException { assertFalse(root.hasProperty(NodeTypes.Activatable.LAST_ACTIVATED)); assertNull(new MetaData(root).getLastActionDate()); root.setProperty(NodeTypes.Activatable.LAST_ACTIVATED, Calendar.getInstance()); assertTrue(root.hasProperty(NodeTypes.Activatable.LAST_ACTIVATED)); assertNotNull(new MetaData(root).getLastActionDate()); } |
### Question:
MetaData { public void setModificationDate() { Calendar value = new GregorianCalendar(TimeZone.getDefault()); setProperty(LAST_MODIFIED, value); } protected MetaData(Node workingNode, AccessManager ignoredAccessManager); MetaData(Node workingNode); String getTitle(); void setTitle(String value); void setCreationDate(); Calendar getCreationDate(); void setActivated(); void setUnActivated(); boolean getIsActivated(); int getActivationStatus(); void setLastActivationActionDate(); Calendar getLastActionDate(); void setModificationDate(); Calendar getModificationDate(); String getAuthorId(); void setAuthorId(String value); String getActivatorId(); void setActivatorId(String value); String getTemplate(); void setTemplate(String value); void setProperty(String name, String value); void setProperty(String name, long value); void setProperty(String name, double value); void setProperty(String name, boolean value); void setProperty(String name, Calendar value); boolean getBooleanProperty(String name); double getDoubleProperty(String name); long getLongProperty(String name); String getStringProperty(String name); Calendar getDateProperty(String name); void removeProperty(String name); static final String TITLE; static final String CREATION_DATE; static final String LAST_MODIFIED; static final String LAST_ACTION; static final String AUTHOR_ID; static final String ACTIVATOR_ID; static final String TEMPLATE; static final String TEMPLATE_TYPE; static final String ACTIVATED; static final String DEFAULT_META_NODE; static final int ACTIVATION_STATUS_NOT_ACTIVATED; static final int ACTIVATION_STATUS_MODIFIED; static final int ACTIVATION_STATUS_ACTIVATED; }### Answer:
@Test public void testSetModificationDate() throws RepositoryException { assertFalse(root.hasProperty(NodeTypes.LastModified.LAST_MODIFIED)); new MetaData(root).setModificationDate(); assertTrue(root.hasProperty(NodeTypes.LastModified.LAST_MODIFIED)); } |
### Question:
MetaData { public String getAuthorId() { return getStringProperty(AUTHOR_ID); } protected MetaData(Node workingNode, AccessManager ignoredAccessManager); MetaData(Node workingNode); String getTitle(); void setTitle(String value); void setCreationDate(); Calendar getCreationDate(); void setActivated(); void setUnActivated(); boolean getIsActivated(); int getActivationStatus(); void setLastActivationActionDate(); Calendar getLastActionDate(); void setModificationDate(); Calendar getModificationDate(); String getAuthorId(); void setAuthorId(String value); String getActivatorId(); void setActivatorId(String value); String getTemplate(); void setTemplate(String value); void setProperty(String name, String value); void setProperty(String name, long value); void setProperty(String name, double value); void setProperty(String name, boolean value); void setProperty(String name, Calendar value); boolean getBooleanProperty(String name); double getDoubleProperty(String name); long getLongProperty(String name); String getStringProperty(String name); Calendar getDateProperty(String name); void removeProperty(String name); static final String TITLE; static final String CREATION_DATE; static final String LAST_MODIFIED; static final String LAST_ACTION; static final String AUTHOR_ID; static final String ACTIVATOR_ID; static final String TEMPLATE; static final String TEMPLATE_TYPE; static final String ACTIVATED; static final String DEFAULT_META_NODE; static final int ACTIVATION_STATUS_NOT_ACTIVATED; static final int ACTIVATION_STATUS_MODIFIED; static final int ACTIVATION_STATUS_ACTIVATED; }### Answer:
@Test public void testGetAuthorId() throws RepositoryException { assertFalse(root.hasProperty(NodeTypes.LastModified.LAST_MODIFIED_BY)); assertEquals("", new MetaData(root).getAuthorId()); root.setProperty(NodeTypes.LastModified.LAST_MODIFIED_BY, "superuser"); assertTrue(root.hasProperty(NodeTypes.LastModified.LAST_MODIFIED_BY)); assertNotNull(new MetaData(root).getAuthorId()); } |
### Question:
MetaData { public void setAuthorId(String value) { setProperty(AUTHOR_ID, value); } protected MetaData(Node workingNode, AccessManager ignoredAccessManager); MetaData(Node workingNode); String getTitle(); void setTitle(String value); void setCreationDate(); Calendar getCreationDate(); void setActivated(); void setUnActivated(); boolean getIsActivated(); int getActivationStatus(); void setLastActivationActionDate(); Calendar getLastActionDate(); void setModificationDate(); Calendar getModificationDate(); String getAuthorId(); void setAuthorId(String value); String getActivatorId(); void setActivatorId(String value); String getTemplate(); void setTemplate(String value); void setProperty(String name, String value); void setProperty(String name, long value); void setProperty(String name, double value); void setProperty(String name, boolean value); void setProperty(String name, Calendar value); boolean getBooleanProperty(String name); double getDoubleProperty(String name); long getLongProperty(String name); String getStringProperty(String name); Calendar getDateProperty(String name); void removeProperty(String name); static final String TITLE; static final String CREATION_DATE; static final String LAST_MODIFIED; static final String LAST_ACTION; static final String AUTHOR_ID; static final String ACTIVATOR_ID; static final String TEMPLATE; static final String TEMPLATE_TYPE; static final String ACTIVATED; static final String DEFAULT_META_NODE; static final int ACTIVATION_STATUS_NOT_ACTIVATED; static final int ACTIVATION_STATUS_MODIFIED; static final int ACTIVATION_STATUS_ACTIVATED; }### Answer:
@Test public void testSetAuthorId() throws RepositoryException { assertFalse(root.hasProperty(NodeTypes.LastModified.LAST_MODIFIED_BY)); new MetaData(root).setAuthorId("superuser"); assertTrue(root.hasProperty(NodeTypes.LastModified.LAST_MODIFIED_BY)); } |
### Question:
MetaData { public String getActivatorId() { return getStringProperty(ACTIVATOR_ID); } protected MetaData(Node workingNode, AccessManager ignoredAccessManager); MetaData(Node workingNode); String getTitle(); void setTitle(String value); void setCreationDate(); Calendar getCreationDate(); void setActivated(); void setUnActivated(); boolean getIsActivated(); int getActivationStatus(); void setLastActivationActionDate(); Calendar getLastActionDate(); void setModificationDate(); Calendar getModificationDate(); String getAuthorId(); void setAuthorId(String value); String getActivatorId(); void setActivatorId(String value); String getTemplate(); void setTemplate(String value); void setProperty(String name, String value); void setProperty(String name, long value); void setProperty(String name, double value); void setProperty(String name, boolean value); void setProperty(String name, Calendar value); boolean getBooleanProperty(String name); double getDoubleProperty(String name); long getLongProperty(String name); String getStringProperty(String name); Calendar getDateProperty(String name); void removeProperty(String name); static final String TITLE; static final String CREATION_DATE; static final String LAST_MODIFIED; static final String LAST_ACTION; static final String AUTHOR_ID; static final String ACTIVATOR_ID; static final String TEMPLATE; static final String TEMPLATE_TYPE; static final String ACTIVATED; static final String DEFAULT_META_NODE; static final int ACTIVATION_STATUS_NOT_ACTIVATED; static final int ACTIVATION_STATUS_MODIFIED; static final int ACTIVATION_STATUS_ACTIVATED; }### Answer:
@Test public void testGetActivatorId() throws RepositoryException { assertFalse(root.hasProperty(NodeTypes.Activatable.LAST_ACTIVATED_BY)); assertEquals("", new MetaData(root).getActivatorId()); root.setProperty(NodeTypes.Activatable.LAST_ACTIVATED_BY, "superuser"); assertTrue(root.hasProperty(NodeTypes.Activatable.LAST_ACTIVATED_BY)); assertNotNull(new MetaData(root).getActivatorId()); } |
### Question:
MetaData { public void setActivatorId(String value) { setProperty(ACTIVATOR_ID, value); } protected MetaData(Node workingNode, AccessManager ignoredAccessManager); MetaData(Node workingNode); String getTitle(); void setTitle(String value); void setCreationDate(); Calendar getCreationDate(); void setActivated(); void setUnActivated(); boolean getIsActivated(); int getActivationStatus(); void setLastActivationActionDate(); Calendar getLastActionDate(); void setModificationDate(); Calendar getModificationDate(); String getAuthorId(); void setAuthorId(String value); String getActivatorId(); void setActivatorId(String value); String getTemplate(); void setTemplate(String value); void setProperty(String name, String value); void setProperty(String name, long value); void setProperty(String name, double value); void setProperty(String name, boolean value); void setProperty(String name, Calendar value); boolean getBooleanProperty(String name); double getDoubleProperty(String name); long getLongProperty(String name); String getStringProperty(String name); Calendar getDateProperty(String name); void removeProperty(String name); static final String TITLE; static final String CREATION_DATE; static final String LAST_MODIFIED; static final String LAST_ACTION; static final String AUTHOR_ID; static final String ACTIVATOR_ID; static final String TEMPLATE; static final String TEMPLATE_TYPE; static final String ACTIVATED; static final String DEFAULT_META_NODE; static final int ACTIVATION_STATUS_NOT_ACTIVATED; static final int ACTIVATION_STATUS_MODIFIED; static final int ACTIVATION_STATUS_ACTIVATED; }### Answer:
@Test public void testSetActivatorId() throws RepositoryException { assertFalse(root.hasProperty(NodeTypes.Activatable.LAST_ACTIVATED_BY)); new MetaData(root).setActivatorId("superuser"); assertTrue(root.hasProperty(NodeTypes.Activatable.LAST_ACTIVATED_BY)); } |
### Question:
MetaData { public String getTemplate() { return getStringProperty(TEMPLATE); } protected MetaData(Node workingNode, AccessManager ignoredAccessManager); MetaData(Node workingNode); String getTitle(); void setTitle(String value); void setCreationDate(); Calendar getCreationDate(); void setActivated(); void setUnActivated(); boolean getIsActivated(); int getActivationStatus(); void setLastActivationActionDate(); Calendar getLastActionDate(); void setModificationDate(); Calendar getModificationDate(); String getAuthorId(); void setAuthorId(String value); String getActivatorId(); void setActivatorId(String value); String getTemplate(); void setTemplate(String value); void setProperty(String name, String value); void setProperty(String name, long value); void setProperty(String name, double value); void setProperty(String name, boolean value); void setProperty(String name, Calendar value); boolean getBooleanProperty(String name); double getDoubleProperty(String name); long getLongProperty(String name); String getStringProperty(String name); Calendar getDateProperty(String name); void removeProperty(String name); static final String TITLE; static final String CREATION_DATE; static final String LAST_MODIFIED; static final String LAST_ACTION; static final String AUTHOR_ID; static final String ACTIVATOR_ID; static final String TEMPLATE; static final String TEMPLATE_TYPE; static final String ACTIVATED; static final String DEFAULT_META_NODE; static final int ACTIVATION_STATUS_NOT_ACTIVATED; static final int ACTIVATION_STATUS_MODIFIED; static final int ACTIVATION_STATUS_ACTIVATED; }### Answer:
@Test public void testGetTemplate() throws RepositoryException { assertFalse(root.hasProperty(NodeTypes.Renderable.TEMPLATE)); assertEquals("", new MetaData(root).getTemplate()); root.setProperty(NodeTypes.Renderable.TEMPLATE, "samples:pages/main"); assertTrue(root.hasProperty(NodeTypes.Renderable.TEMPLATE)); assertNotNull(new MetaData(root).getTemplate()); } |
### Question:
MetaData { public void setTemplate(String value) { setProperty(TEMPLATE, value); } protected MetaData(Node workingNode, AccessManager ignoredAccessManager); MetaData(Node workingNode); String getTitle(); void setTitle(String value); void setCreationDate(); Calendar getCreationDate(); void setActivated(); void setUnActivated(); boolean getIsActivated(); int getActivationStatus(); void setLastActivationActionDate(); Calendar getLastActionDate(); void setModificationDate(); Calendar getModificationDate(); String getAuthorId(); void setAuthorId(String value); String getActivatorId(); void setActivatorId(String value); String getTemplate(); void setTemplate(String value); void setProperty(String name, String value); void setProperty(String name, long value); void setProperty(String name, double value); void setProperty(String name, boolean value); void setProperty(String name, Calendar value); boolean getBooleanProperty(String name); double getDoubleProperty(String name); long getLongProperty(String name); String getStringProperty(String name); Calendar getDateProperty(String name); void removeProperty(String name); static final String TITLE; static final String CREATION_DATE; static final String LAST_MODIFIED; static final String LAST_ACTION; static final String AUTHOR_ID; static final String ACTIVATOR_ID; static final String TEMPLATE; static final String TEMPLATE_TYPE; static final String ACTIVATED; static final String DEFAULT_META_NODE; static final int ACTIVATION_STATUS_NOT_ACTIVATED; static final int ACTIVATION_STATUS_MODIFIED; static final int ACTIVATION_STATUS_ACTIVATED; }### Answer:
@Test public void testSetTemplate() throws RepositoryException { assertFalse(root.hasProperty(NodeTypes.Renderable.TEMPLATE)); new MetaData(root).setTemplate("samples:pages/main"); assertTrue(root.hasProperty(NodeTypes.Renderable.TEMPLATE)); } |
### Question:
Path { public static boolean isAbsolute(String path) { if (path == null) { return false; } if (path.startsWith("/") || path.startsWith(File.separator)) { return true; } if (path.length() >= 3 && Character.isLetter(path.charAt(0)) && path.charAt(1) == ':') { return true; } return false; } private Path(); static String getCacheDirectoryPath(); static File getCacheDirectory(); static String getTempDirectoryPath(); static File getTempDirectory(); static String getHistoryFilePath(); static File getHistoryFile(); static String getRepositoriesConfigFilePath(); static File getRepositoriesConfigFile(); static File getAppRootDir(); static String getAbsoluteFileSystemPath(String path); static String getUniqueLabel(HierarchyManager hierarchyManager, String parent, String label); static String getUniqueLabel(Session session, String parent, String label); static String getUniqueLabel(Content parent, String label); static boolean isAbsolute(String path); static String getValidatedLabel(String label); static String getValidatedLabel(String label, String charset); static boolean isCharValid(int charCode, String charset); static String getAbsolutePath(String path, String label); static String getAbsolutePath(String path); @Deprecated static String getNodePath(String path, String label); @Deprecated static String getNodePath(String path); @Deprecated static String getParentPath(String path); static final String SELECTOR_DELIMITER; }### Answer:
@Test public void testIsAbsolute() { assertTrue(Path.isAbsolute("/test")); assertTrue(Path.isAbsolute("d:/test")); assertTrue(Path.isAbsolute(File.separator + "test")); assertFalse(Path.isAbsolute("test")); } |
### Question:
Path { public static String getAbsoluteFileSystemPath(String path) { if (isAbsolute(path)) { return path; } return new File(getAppRootDir(), path).getAbsolutePath(); } private Path(); static String getCacheDirectoryPath(); static File getCacheDirectory(); static String getTempDirectoryPath(); static File getTempDirectory(); static String getHistoryFilePath(); static File getHistoryFile(); static String getRepositoriesConfigFilePath(); static File getRepositoriesConfigFile(); static File getAppRootDir(); static String getAbsoluteFileSystemPath(String path); static String getUniqueLabel(HierarchyManager hierarchyManager, String parent, String label); static String getUniqueLabel(Session session, String parent, String label); static String getUniqueLabel(Content parent, String label); static boolean isAbsolute(String path); static String getValidatedLabel(String label); static String getValidatedLabel(String label, String charset); static boolean isCharValid(int charCode, String charset); static String getAbsolutePath(String path, String label); static String getAbsolutePath(String path); @Deprecated static String getNodePath(String path, String label); @Deprecated static String getNodePath(String path); @Deprecated static String getParentPath(String path); static final String SELECTOR_DELIMITER; }### Answer:
@Test public void testGetAbsoluteFileSystemPathReturnsArgumentIfPathIsAbsolute() throws Exception { String absPath = "/foo/bar"; String returnedPath = Path.getAbsoluteFileSystemPath(absPath); assertEquals(absPath, returnedPath); } |
### Question:
VersionedNode extends PropertyAndChildWrappingNodeWrapper implements Version { @Override public Property wrapProperty(Property property) { return new DelegatePropertyWrapper(property) { @Override public String getPath() throws RepositoryException { return VersionedNode.this.getPath() + "/" + getName(); } }; } VersionedNode(Version versionedNode, Node baseNode); @Override int getDepth(); @Override Item getAncestor(int depth); Version unwrap(); @Override VersionHistory getContainingHistory(); @Override Calendar getCreated(); @Override Node getFrozenNode(); @Override Version getLinearPredecessor(); @Override Version getLinearSuccessor(); @Override Version[] getPredecessors(); @Override Version[] getSuccessors(); @Override Node wrapNode(Node node); @Override Property wrapProperty(Property property); @Override String getPath(); @Override Node getParent(); @Override boolean isNodeType(String nodeTypeName); @Override NodeType getPrimaryNodeType(); Node getBaseNode(); @Override Session getSession(); }### Answer:
@Test public void testWrapProperty() throws Exception { final Version v = mock(Version.class); final Node baseNode = mock(Node.class); when(baseNode.getPath()).thenReturn("baseNodePath"); final VersionedNode vn = new VersionedNode(v, baseNode); final Property property2Wrap = mock(Property.class); when(property2Wrap.getName()).thenReturn("nameOfProperty2Wrap"); final Property wrapped = vn.wrapProperty(property2Wrap); final String path = wrapped.getPath(); assertEquals("baseNodePath/nameOfProperty2Wrap", path); } |
### Question:
BaseVersionManager { protected Session getSession() throws LoginException, RepositoryException { return MgnlContext.getSystemContext().getJCRSession(VersionManager.VERSION_WORKSPACE); } synchronized Version addVersion(Node node); synchronized Version addVersion(final Node node, final Rule rule); abstract boolean isInvalidMaxVersions(); synchronized Node getVersionedNode(Node node); abstract void setMaxVersionHistory(Node node); synchronized VersionHistory getVersionHistory(Node node); synchronized Version getVersion(Node node, String name); Version getBaseVersion(Node node); synchronized VersionIterator getAllVersions(Node node); @Deprecated synchronized void restore(Content node, Version version, boolean removeExisting); synchronized void restore(final Node node, Version version, boolean removeExisting); synchronized void removeVersionHistory(final Node node); static final String VERSION_WORKSPACE; static final String TMP_REFERENCED_NODES; static final String PROPERTY_RULE; }### Answer:
@Test public void testUseSystemSessionToRetrieveVersions() throws RepositoryException { Session session = MgnlContext.getSystemContext().getJCRSession(RepositoryConstants.VERSION_STORE); VersionManager versionMan = VersionManager.getInstance(); assertSame(session, versionMan.getSession()); } |
### Question:
ContentTypeFilter extends AbstractMgnlFilter { protected String setupContentTypeAndCharacterEncoding(String extension, HttpServletRequest request, HttpServletResponse response) { final String mimeType = MIMEMapping.getMIMETypeOrDefault(extension); final String characterEncoding = MIMEMapping.getContentEncodingOrDefault(mimeType); try { if (request.getCharacterEncoding() == null) { request.setCharacterEncoding(characterEncoding); } } catch (UnsupportedEncodingException e) { log.error("Can't set character encoding for the request (extension=" + extension + ",mimetype=" + mimeType + ")", e); } response.setCharacterEncoding(characterEncoding); response.setContentType(mimeType); return characterEncoding; } @Override void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain); }### Answer:
@Test public void testFilterWithEmptyDefaultExtension() { filter.setupContentTypeAndCharacterEncoding("", request, response); verify(response).setCharacterEncoding("UTF-8"); verify(response).setContentType(null); } |
### Question:
WorkspaceMapping { public Repository getRepository(String repositoryId) { Repository repository = repositories.get(repositoryId); if (repository == null) { final String s = "Failed to retrieve repository '" + repositoryId + "'. Your Magnolia instance might not have been initialized properly."; log.warn(s); throw new IllegalArgumentException(s); } return repository; } void clearRepositories(); void clearAll(); void addRepositoryDefinition(RepositoryDefinition repositoryDefinition); void addWorkspaceMapping(WorkspaceMappingDefinition mapping); void addWorkspaceMappingDefinition(WorkspaceMappingDefinition definition); RepositoryDefinition getRepositoryDefinition(String repositoryId); Collection<String> getLogicalWorkspaceNames(); WorkspaceMappingDefinition getWorkspaceMapping(String logicalWorkspaceName); Collection<WorkspaceMappingDefinition> getWorkspaceMappings(); void setRepository(String repositoryId, Repository repository); void setRepositoryProvider(String repositoryId, Provider provider); Repository getRepository(String repositoryId); Provider getRepositoryProvider(String repositoryId); Collection<RepositoryDefinition> getRepositoryDefinitions(); }### Answer:
@Test @Ignore public void testUnknownRepositoryShouldYieldMeaningfulExceptionMessage() { WorkspaceMapping mapping = new WorkspaceMapping(); try { mapping.getRepository("dummy"); fail("should have failed, since we haven't set any repository at all"); } catch (Throwable t) { assertEquals("Failed to retrieve repository 'dummy' (mapped as 'dummy'). Your Magnolia instance might not have been initialized properly.", t.getMessage()); } } |
### Question:
Ops { public static NodeOperation addProperty(final String name, final Object value) { return new AbstractNodeOperation() { @Override protected Content doExec(Content context, ErrorHandler errorHandler) throws RepositoryException { if (context.hasNodeData(name)) { throw new ItemExistsException(name); } context.createNodeData(name, value); return context; } }; } static NodeOperation addNode(final String name); static NodeOperation addNode(final String name, final String type); static NodeOperation addNode(final String name, final ItemType type); static NodeOperation getNode(final String name); static NodeOperation remove(final String name); static NodeOperation addProperty(final String name, final Object value); static NodeOperation setProperty(final String name, final Object newValue); static NodeOperation setProperty(final String name, final Object expectedCurrentValue, 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 copyNode(final String nodeName, final String dest); static NodeOperation onChildNodes(final NodeOperation... childrenOps); static NodeOperation onChildNodes(final String type, final NodeOperation... childrenOps); static NodeOperation onChildNodes(final ItemType type, final NodeOperation... childrenOps); static NodeOperation onChildNodes(final Content.ContentFilter filter, final NodeOperation... childrenOps); static NodeOperation noop(); }### Answer:
@Test public void testAddPropertyFailsIfPropertyExists() throws Exception { final HierarchyManager hm = MgnlContext.getHierarchyManager("config"); final Content node = hm.getRoot().createContent("hello"); node.createNodeData("foo", "bar"); hm.save(); try { final NodeOperation op = Ops.addProperty("foo", "zazoo"); op.exec(node, eh); fail("should have failed"); } catch (Throwable e) { assertEquals("foo", e.getMessage()); } } |
### Question:
Ops { public static NodeOperation remove(final String name) { return new AbstractNodeOperation() { @Override protected Content doExec(Content context, ErrorHandler errorHandler) throws RepositoryException { context.delete(name); return context; } }; } static NodeOperation addNode(final String name); static NodeOperation addNode(final String name, final String type); static NodeOperation addNode(final String name, final ItemType type); static NodeOperation getNode(final String name); static NodeOperation remove(final String name); static NodeOperation addProperty(final String name, final Object value); static NodeOperation setProperty(final String name, final Object newValue); static NodeOperation setProperty(final String name, final Object expectedCurrentValue, 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 copyNode(final String nodeName, final String dest); static NodeOperation onChildNodes(final NodeOperation... childrenOps); static NodeOperation onChildNodes(final String type, final NodeOperation... childrenOps); static NodeOperation onChildNodes(final ItemType type, final NodeOperation... childrenOps); static NodeOperation onChildNodes(final Content.ContentFilter filter, final NodeOperation... childrenOps); static NodeOperation noop(); }### Answer:
@Test public void testRemoveFailsOnUnexistingPropertyOrNode() throws Exception { final HierarchyManager hm = MgnlContext.getHierarchyManager("config"); hm.getRoot().createContent("hello").createNodeData("foo", "bar"); hm.save(); final Content root = hm.getContent("/hello"); try { final NodeOperation op = Ops.remove("non-existing"); op.exec(root, eh); fail("should have failed"); } catch (Throwable e) { assertEquals("non-existing", e.getMessage()); } } |
### Question:
ContentOps { public static NodeOperation createContent(String name, ItemType type) { return Ops.addNode(name, type); } static NodeOperation createContent(String name, ItemType type); static NodeOperation createPage(String name, String template); static NodeOperation createCollectionNode(String name); static NodeOperation createParagraph(String name, String template); static NodeOperation setNodeData(final String name, final Object value); static NodeOperation setBinaryNodeData(final String name, final String fileName, final long size, final InputStream inputStream); static NodeOperation setTemplate(final String template); }### Answer:
@Test public void testCreateContent() throws RepositoryException { MockContent root = new MockContent(ROOT_NAME); ContentOps.createContent(NEW_CONTENT_NAME, ItemType.CONTENTNODE).exec(root, ERROR_HANDLER); assertTrue(root.hasContent(NEW_CONTENT_NAME)); assertEquals(ItemType.CONTENTNODE, root.getContent(NEW_CONTENT_NAME).getItemType()); } |
### Question:
ContentOps { public static NodeOperation createCollectionNode(String name) { return createContent(name, ItemType.CONTENTNODE); } static NodeOperation createContent(String name, ItemType type); static NodeOperation createPage(String name, String template); static NodeOperation createCollectionNode(String name); static NodeOperation createParagraph(String name, String template); static NodeOperation setNodeData(final String name, final Object value); static NodeOperation setBinaryNodeData(final String name, final String fileName, final long size, final InputStream inputStream); static NodeOperation setTemplate(final String template); }### Answer:
@Test public void testCreateCollectionNode() throws RepositoryException { MockContent root = new MockContent(ROOT_NAME); ContentOps.createCollectionNode(NEW_CONTENT_NAME).exec(root, ERROR_HANDLER); assertTrue(root.hasContent(NEW_CONTENT_NAME)); assertEquals(ItemType.CONTENTNODE, root.getContent(NEW_CONTENT_NAME).getItemType()); } |
### Question:
ContentOps { public static NodeOperation setNodeData(final String name, final Object value) { return new AbstractNodeOperation() { @Override protected Content doExec(Content context, ErrorHandler errorHandler) throws RepositoryException { context.setNodeData(name, value); return context; } }; } static NodeOperation createContent(String name, ItemType type); static NodeOperation createPage(String name, String template); static NodeOperation createCollectionNode(String name); static NodeOperation createParagraph(String name, String template); static NodeOperation setNodeData(final String name, final Object value); static NodeOperation setBinaryNodeData(final String name, final String fileName, final long size, final InputStream inputStream); static NodeOperation setTemplate(final String template); }### Answer:
@Test public void testSetNodeData() { MockContent content = new MockContent(NEW_CONTENT_NAME); ContentOps.setNodeData(NODEDATA_NAME, NODEDATA_VALUE).exec(content, ERROR_HANDLER); assertEquals(NODEDATA_VALUE, content.getNodeData(NODEDATA_NAME).getString()); } |
### Question:
ContentOps { public static NodeOperation setBinaryNodeData(final String name, final String fileName, final long size, final InputStream inputStream) { return new AbstractNodeOperation() { @Override protected Content doExec(Content context, ErrorHandler errorHandler) throws RepositoryException { NodeData binary = context.setNodeData(name, inputStream); binary.setAttribute(FileProperties.PROPERTY_FILENAME, StringUtils.substringBeforeLast(fileName, ".")); binary.setAttribute(FileProperties.PROPERTY_EXTENSION, StringUtils.substringAfterLast(fileName, ".")); binary.setAttribute(FileProperties.PROPERTY_SIZE, Long.toString(size)); return context; } }; } static NodeOperation createContent(String name, ItemType type); static NodeOperation createPage(String name, String template); static NodeOperation createCollectionNode(String name); static NodeOperation createParagraph(String name, String template); static NodeOperation setNodeData(final String name, final Object value); static NodeOperation setBinaryNodeData(final String name, final String fileName, final long size, final InputStream inputStream); static NodeOperation setTemplate(final String template); }### Answer:
@Test public void testSetBinaryNodeData() throws IOException { MockContent content = new MockContent(NEW_CONTENT_NAME); byte[] bytes = {'C', 'O', 'N', 'T', 'E', 'N', 'T'}; ContentOps.setBinaryNodeData(NODEDATA_NAME, "test.jpg", bytes.length, new ByteArrayInputStream(bytes)).exec(content, ERROR_HANDLER); NodeData nodeData = content.getNodeData(NODEDATA_NAME); assertEquals("test", nodeData.getAttribute(FileProperties.PROPERTY_FILENAME)); assertEquals("jpg", nodeData.getAttribute(FileProperties.PROPERTY_EXTENSION)); assertEquals(String.valueOf(bytes.length), nodeData.getAttribute(FileProperties.PROPERTY_SIZE)); InputStream stream = nodeData.getStream(); assertEquals(new String(bytes), IOUtils.toString(stream)); } |
### Question:
SimpleContext extends AbstractMapBasedContext { @Override public Session getJCRSession(String workspaceName) throws LoginException, RepositoryException { return this.ctx.getJCRSession(workspaceName); } SimpleContext(); SimpleContext(Map<String, Object> map); @Override AccessManager getAccessManager(String workspaceId); @Override HierarchyManager getHierarchyManager(String workspaceId); @Override Session getJCRSession(String workspaceName); @Override User getUser(); @Override QueryManager getQueryManager(String workspaceId); @Override void release(); }### Answer:
@Test public void testSimpleContextDelegateGetJCRSessionMethod() throws Exception { ComponentsTestUtil.setInstance(SystemContext.class, new JCRSessionPerThreadSystemContext()); MgnlContext.setInstance(new SimpleContext(Components.getComponent(SystemContext.class))); assertNotNull(MgnlContext.getJCRSession("website")); } |
### Question:
DefaultRepositoryStrategy extends AbstractRepositoryStrategy { protected Credentials getCredentials() { User user = MgnlContext.getUser(); if (user == null) { String user1 = SystemProperty.getProperty("magnolia.connection.jcr.anonymous.userId", "anonymous"); String pwd = SystemProperty.getProperty("magnolia.connection.jcr.anonymous.password", "anonymous"); return new SimpleCredentials(user1, pwd.toCharArray()); } final String password = user.getPassword(); if (password == null) { return new SimpleCredentials(user.getName(), "".toCharArray()); } else { return new SimpleCredentials(user.getName(), password.toCharArray()); } } @Inject DefaultRepositoryStrategy(RepositoryManager repositoryManager, UserContext context); @Override void release(); }### Answer:
@Test public void testGetUserCredentialsReturnsCredentialsFromContextUserIfSet() { Context context = mock(Context.class); MgnlContext.setInstance(context); User user = mock(User.class); when(context.getUser()).thenReturn(user); when(user.getName()).thenReturn("user"); when(user.getPassword()).thenReturn("password"); SimpleCredentials credentials = (SimpleCredentials) strategy.getCredentials(); assertEquals("user", credentials.getUserID()); assertEquals("password", new String(credentials.getPassword())); }
@Test public void testPasswordIsNull() { Context context = mock(Context.class); MgnlContext.setInstance(context); User user = mock(User.class); when(context.getUser()).thenReturn(user); when(user.getName()).thenReturn("user"); when(user.getPassword()).thenReturn(null); SimpleCredentials credentials = (SimpleCredentials) strategy.getCredentials(); assertEquals("user", credentials.getUserID()); assertEquals("", new String(credentials.getPassword())); } |
### Question:
AbstractRepositoryStrategy implements JCRSessionStrategy { @Override public Session getSession(String workspaceName) throws LoginException, RepositoryException { Session jcrSession = jcrSessions.get(workspaceName); if (jcrSession == null) { log.debug("creating jcr session {} by thread {}", workspaceName, Thread.currentThread().getName()); jcrSession = internalGetSession(workspaceName); jcrSessions.put(workspaceName, jcrSession); } return jcrSession; } @Inject protected AbstractRepositoryStrategy(RepositoryManager repositoryManager); @Override Session getSession(String workspaceName); }### Answer:
@Test public void testGetSession() throws Exception { Session session = strategy.getSession("website"); assertNotNull(session); strategy.release(); } |
### Question:
MetaDataImportPostProcessor implements ImportPostProcessor { @Override public void postProcessNode(Node node) throws RepositoryException { MetaDataAsMixinConversionHelper conversionHelper = new MetaDataAsMixinConversionHelper(); conversionHelper.setDeleteMetaDataIfEmptied(true); conversionHelper.setPeriodicSaves(false); conversionHelper.convertNodeAndChildren(node); } @Override void postProcessNode(Node node); }### Answer:
@Test public void testMetaDataPropertiesAreConverted() throws RepositoryException { Session session = MgnlContext.getJCRSession("config"); Node node = session.getRootNode().addNode("test"); Node md = node.addNode("MetaData", NodeTypes.MetaData.NAME); Calendar calendar = Calendar.getInstance(); md.setProperty("mgnl:creationdate", calendar); md.setProperty("mgnl:lastaction", calendar); md.setProperty("mgnl:activatorid", "superuser"); md.setProperty("mgnl:activated", "2"); md.setProperty("mgnl:template", "samples:pages/some/page"); md.setProperty("mgnl:authorid", "hyperuser"); md.setProperty("mgnl:lastmodified", calendar); node.setProperty("mgnl:deletedOn", calendar); new MetaDataImportPostProcessor().postProcessNode(node); assertPropertyEquals(node, NodeTypes.Created.CREATED, calendar); assertPropertyEquals(node, NodeTypes.Activatable.LAST_ACTIVATED, calendar); assertPropertyEquals(node, NodeTypes.Activatable.LAST_ACTIVATED_BY, "superuser"); assertPropertyEquals(node, NodeTypes.Activatable.ACTIVATION_STATUS, "2"); assertPropertyEquals(node, NodeTypes.Renderable.TEMPLATE, "samples:pages/some/page"); assertPropertyEquals(node, NodeTypes.LastModified.LAST_MODIFIED_BY, "hyperuser"); assertPropertyEquals(node, NodeTypes.LastModified.LAST_MODIFIED, calendar); assertPropertyEquals(node, NodeTypes.Deleted.DELETED, calendar); } |
### Question:
BootstrapUtil { public static String getWorkspaceNameFromResource(final String resourcePath) { String resourceName = StringUtils.replace(resourcePath, "\\", "/"); String name = getFilenameFromResource(resourceName, ".xml"); String fullPath = DataTransporter.revertExportPath(name); return StringUtils.substringBefore(fullPath, "/"); } static void bootstrap(String[] resourceNames, int importUUIDBehavior); static void export(Content content, File directory); static String getWorkspaceNameFromResource(final String resourcePath); static String getFullpathFromResource(final String resourcePath); static String getPathnameFromResource(final String resourcePath); static String getFilenameFromResource(final String resourcePath, final String extension); }### Answer:
@Test public void testGetWorkspaceNameFromResource() throws Exception { String workspace = BootstrapUtil.getWorkspaceNameFromResource(MGNL_BOOTSTRAP_FILE); assertEquals("config", workspace); workspace = BootstrapUtil.getWorkspaceNameFromResource(MGNL_BOOTSTRAP_FILE_NEW_STYLE); assertEquals("config", workspace); } |
### Question:
BootstrapUtil { public static String getPathnameFromResource(final String resourcePath) { String resourceName = StringUtils.replace(resourcePath, "\\", "/"); String name = getFilenameFromResource(resourceName, ".xml"); String fullPath = DataTransporter.revertExportPath(name); String pathName = StringUtils.substringAfter(StringUtils.substringBeforeLast(fullPath, "/"), "/"); if(!pathName.startsWith("/")) { pathName = "/" + pathName; } return pathName; } static void bootstrap(String[] resourceNames, int importUUIDBehavior); static void export(Content content, File directory); static String getWorkspaceNameFromResource(final String resourcePath); static String getFullpathFromResource(final String resourcePath); static String getPathnameFromResource(final String resourcePath); static String getFilenameFromResource(final String resourcePath, final String extension); }### Answer:
@Test public void testGetPathnameFromResource() throws Exception { String pathname = BootstrapUtil.getPathnameFromResource(MGNL_BOOTSTRAP_FILE); assertEquals("/server", pathname); pathname = BootstrapUtil.getPathnameFromResource(MGNL_BOOTSTRAP_FILE_NEW_STYLE); assertEquals("/server", pathname); pathname = BootstrapUtil.getPathnameFromResource(MGNL_BOOTSTRAP_FILE_NEW_STYLE_NO_SLASHES); assertEquals("/server", pathname); } |
### Question:
BootstrapUtil { public static String getFullpathFromResource(final String resourcePath) { String resourceName = StringUtils.replace(resourcePath, "\\", "/"); String name = getFilenameFromResource(resourceName, ".xml"); String fullPath = DataTransporter.revertExportPath(name); String repository = StringUtils.substringBefore(fullPath, "/"); return StringUtils.removeStart(fullPath, repository); } static void bootstrap(String[] resourceNames, int importUUIDBehavior); static void export(Content content, File directory); static String getWorkspaceNameFromResource(final String resourcePath); static String getFullpathFromResource(final String resourcePath); static String getPathnameFromResource(final String resourcePath); static String getFilenameFromResource(final String resourcePath, final String extension); }### Answer:
@Test public void testGetFullpathFromResource() throws Exception { String fullpath = BootstrapUtil.getFullpathFromResource(MGNL_BOOTSTRAP_FILE); assertEquals("/server/i18n", fullpath); fullpath = BootstrapUtil.getFullpathFromResource(MGNL_BOOTSTRAP_FILE_NEW_STYLE); assertEquals("/server/foo.i18n", fullpath); fullpath = BootstrapUtil.getFullpathFromResource(MGNL_BOOTSTRAP_FILE_NEW_STYLE_NO_SLASHES); assertEquals("/server/foo.i18n", fullpath); } |
### Question:
BootstrapUtil { public static String getFilenameFromResource(final String resourcePath, final String extension) { String ext = StringUtils.defaultIfEmpty(extension, ".xml"); String tmpResourcePath = resourcePath; if(resourcePath.contains("/")) { tmpResourcePath = StringUtils.substringAfterLast(resourcePath, "/"); } return StringUtils.removeEnd(tmpResourcePath, ext.startsWith(".") ? ext : "." + ext); } static void bootstrap(String[] resourceNames, int importUUIDBehavior); static void export(Content content, File directory); static String getWorkspaceNameFromResource(final String resourcePath); static String getFullpathFromResource(final String resourcePath); static String getPathnameFromResource(final String resourcePath); static String getFilenameFromResource(final String resourcePath, final String extension); }### Answer:
@Test public void testGetFilenameFromResource() throws Exception { String fileName = BootstrapUtil.getFilenameFromResource(MGNL_BOOTSTRAP_FILE, null); assertEquals("config.server.i18n", fileName); fileName = BootstrapUtil.getFilenameFromResource(MGNL_BOOTSTRAP_FILE, "xml"); assertEquals("config.server.i18n", fileName); fileName = BootstrapUtil.getFilenameFromResource(MGNL_BOOTSTRAP_FILE_NEW_STYLE, null); assertEquals("config.server.foo..i18n", fileName); fileName = BootstrapUtil.getFilenameFromResource("/mgnl-bootstrap/foo/bar..baz.qux", ".qux"); assertEquals("bar..baz", fileName); fileName = BootstrapUtil.getFilenameFromResource(MGNL_BOOTSTRAP_FILE_NEW_STYLE_NO_SLASHES, ".xml"); assertEquals("config.server.foo..i18n", fileName); } |
### Question:
DataTransporter { public static String createExportPath(String path) { String newPath = path.replace(".", ".."); newPath = newPath.replace("/", "."); return newPath; } static synchronized void importDocument(Document xmlDocument, String repositoryName, String basepath,
boolean keepVersionHistory, int importMode, boolean saveAfterImport,
boolean createBasepathIfNotExist); static synchronized void importFile(File xmlFile, String repositoryName, String basepath,
boolean keepVersionHistory, int importMode, boolean saveAfterImport,
boolean createBasepathIfNotExist); static void executeBootstrapImport(File xmlFile, String repositoryName); static void importProperties(Properties properties, String repositoryName); static synchronized void importXmlStream(InputStream xmlStream, String repositoryName, String basepath,
String name, boolean keepVersionHistory, int importMode,
boolean saveAfterImport, boolean createBasepathIfNotExist); static void executeExport(OutputStream baseOutputStream, boolean keepVersionHistory, boolean format,
Session session, String basepath, String repository, String ext); static void parseAndFormat(OutputStream stream, XMLReader reader, String repository, String basepath,
Session session, boolean noRecurse); static String encodePath(String path, String separator, String enc); static String decodePath(String path, String enc); static String createExportPath(String path); static String revertExportPath(String exportPath); static final String ZIP; static final String GZ; static final String XML; static final String PROPERTIES; static final String DOT; static final String SLASH; static final String UTF8; static final String JCR_ROOT; }### Answer:
@Test public void testCreateExportPath() throws Exception { String path = DataTransporter.createExportPath("/foo/bar.baz/test../dir/baz..bar"); assertEquals(".foo.bar..baz.test.....dir.baz....bar", path); path = DataTransporter.createExportPath("/"); assertEquals(".", path); } |
### Question:
ModuleBootstrapTask extends BootstrapResourcesTask { @Override protected boolean acceptResource(InstallContext ctx, String resourceName) { final String moduleName = ctx.getCurrentModuleDefinition().getName(); return resourceName.startsWith("/mgnl-bootstrap/" + moduleName + "/") && resourceName.endsWith(".xml"); } ModuleBootstrapTask(); }### Answer:
@Test public void testShouldOnlyBootstrapFilesFromThisModule() { final ModuleDefinition modDef = new ModuleDefinition("test-module", Version.parseVersion("1.0"), null, null); final InstallContext ctx = createStrictMock(InstallContext.class); expect(ctx.getCurrentModuleDefinition()).andReturn(modDef).anyTimes(); replay(ctx); final ModuleBootstrapTask task = new ModuleBootstrapTask(); assertEquals(true, task.acceptResource(ctx, "/mgnl-bootstrap/test-module/foo.xml")); assertEquals(true, task.acceptResource(ctx, "/mgnl-bootstrap/test-module/foo/bar.xml")); assertEquals(false, task.acceptResource(ctx, "/mgnl-bootstrap/test-module-foo.xml")); assertEquals(false, task.acceptResource(ctx, "/mgnl-bootstrap/test-module.xml")); assertEquals(false, task.acceptResource(ctx, "/mgnl-bootstrap/other-module/foo/bar.xml")); assertEquals(false, task.acceptResource(ctx, "/mgnl-pouet/test-module/foo/bar.xml")); assertEquals(false, task.acceptResource(ctx, "/mgnl-pouet/other-module/foo/bar.xml")); assertEquals(false, task.acceptResource(ctx, "/test-module/foo.xml")); assertEquals(false, task.acceptResource(ctx, "/other-module/foo.xml")); verify(ctx); } |
### Question:
TextFileConditionsUtil { public void addFalseConditionIfExpressionIsContained(String fileName, String regExp) { List<String> matches = TextFileUtil.getTrimmedLinesMatching(fileName, regExp); if (matches.size() > 0) { conditions.add(new FalseCondition("Invalid entries", "The file '" + fileName + "' contains " + matches.size() + " line(s) matching " + regExp + ". Please remove it.")); } } TextFileConditionsUtil(List<Condition> conditions); void addFalseConditionIfExpressionIsNotContained(String fileName, String regExp); void addFalseConditionIfExpressionIsContained(String fileName, String regExp); }### Answer:
@Test public void testAddFalseConditionIfExpressionIsContained() { final String file = "src/test/resources/config/outdated-jaas.config"; util.addFalseConditionIfExpressionIsContained(file, "^Jackrabbit.*"); assertEquals(1, conditions.size()); assertTrue(conditions.get(0) instanceof FalseCondition); assertThat(conditions.get(0).getDescription(), Matchers.containsString(file)); assertThat(conditions.get(0).getDescription(), Matchers.endsWith("Please remove it.")); } |
### Question:
TextFileConditionsUtil { public void addFalseConditionIfExpressionIsNotContained(String fileName, String regExp) { List<String> matches = TextFileUtil.getTrimmedLinesMatching(fileName, regExp); if (matches.isEmpty()) { conditions.add(new FalseCondition("Missing required entries.", "The file '" + fileName + "' must contain a line matching " + regExp + ". Please add it.")); } } TextFileConditionsUtil(List<Condition> conditions); void addFalseConditionIfExpressionIsNotContained(String fileName, String regExp); void addFalseConditionIfExpressionIsContained(String fileName, String regExp); }### Answer:
@Test public void testAddFalseConditionIfExpressionIsNotContained() { final String file = "src/test/resources/config/current-jaas.config"; util.addFalseConditionIfExpressionIsNotContained(file, "^Jackrabbit.*"); assertEquals(1, conditions.size()); assertTrue(conditions.get(0) instanceof FalseCondition); assertThat(conditions.get(0).getDescription(), Matchers.containsString(file)); assertThat(conditions.get(0).getDescription(), Matchers.endsWith("Please add it.")); } |
### Question:
WorkspaceXmlConditionsUtil { public void paramAnalyzerIsNotSet() { List<String> names = WorkspaceXmlUtil.getWorkspaceNamesMatching("/Workspace/SearchIndex/param[@name='analyzer']/@value"); if (names.size() > 0) { for (int i = 0; i < names.size(); i++) { conditions.add(new WarnCondition("workspace.xml updates", "Workspace definition in workspace " + names.get(i) + " Should not have an analyzer set - this will lead to error-logs when strarting up your server.")); } } } WorkspaceXmlConditionsUtil(List<Condition> conditions); void workspaceHasOldIndexer(); void textFilterClassesAreNotSet(); void paramAnalyzerIsNotSet(); void accessControlProviderIsSet(); }### Answer:
@Test public void testParamAnalyzerIsNotAround() { util.paramAnalyzerIsNotSet(); assertEquals(1,conditions.size()); assertTrue(conditions.get(0) instanceof WarnCondition); assertTrue("Received condition was expected to be comming from the outdated config!", conditions.get(0).getDescription().contains("/outdated/workspace.xml")); } |
### Question:
WorkspaceXmlConditionsUtil { public void textFilterClassesAreNotSet() { List<String> names = WorkspaceXmlUtil.getWorkspaceNamesMatching("/Workspace/SearchIndex/param[@name='textFilterClasses']/@value"); if (names.size() > 0) { for (int i = 0; i < names.size(); i++) { conditions.add(new FalseCondition("workspace.xml updates", "Workspace definition in workspace " + names.get(i) + " references indexer which has changed; please remove the parameter 'textFilterClasses'.")); } } } WorkspaceXmlConditionsUtil(List<Condition> conditions); void workspaceHasOldIndexer(); void textFilterClassesAreNotSet(); void paramAnalyzerIsNotSet(); void accessControlProviderIsSet(); }### Answer:
@Test public void testTextFilterClassesAreNotSet() { util.textFilterClassesAreNotSet(); assertEquals(1,conditions.size()); assertTrue(conditions.get(0) instanceof FalseCondition); assertTrue("Received condition was expected to be comming from the outdated config!", conditions.get(0).getDescription().contains("/outdated/workspace.xml")); } |
### Question:
WorkspaceXmlConditionsUtil { public void accessControlProviderIsSet() { List<String> names = WorkspaceXmlUtil.getWorkspaceNames("/Workspace/WorkspaceSecurity/AccessControlProvider/@class", null); if (names.size() > 0) { for (int i = 0; i < names.size(); i++) { conditions.add(new FalseCondition("workspace.xml updates", "Workspace definition in workspace " + names.get(i) + " must have an AccessControlProvider set.")); } } } WorkspaceXmlConditionsUtil(List<Condition> conditions); void workspaceHasOldIndexer(); void textFilterClassesAreNotSet(); void paramAnalyzerIsNotSet(); void accessControlProviderIsSet(); }### Answer:
@Test public void testAccessControlProviderIsSet() { util.accessControlProviderIsSet(); assertEquals(1,conditions.size()); assertTrue(conditions.get(0) instanceof FalseCondition); assertTrue("Received condition was expected to be comming from the outdated config!", conditions.get(0).getDescription().contains("/outdated/workspace.xml")); } |
### Question:
PropertyValuesTask extends AbstractTask { protected void newProperty(InstallContext ctx, Content node, String propertyName, String value) throws RepositoryException { newProperty(ctx, node, propertyName, value, true); } PropertyValuesTask(String name, String description); }### Answer:
@Test public void testNonExistingPropertyAndExpectedAsSuchIsCreated() throws RepositoryException { final MockContent node = new MockContent("foo"); final PropertyValuesTask pvd = new DummyPropertyValuesDelta(); replay(ctx); pvd.newProperty(ctx, node, "bar", "newValue"); verify(ctx); final NodeData nodeData = node.getNodeData("bar"); assertEquals("newValue", nodeData.getString()); }
@Test public void testUnexpectedlyExistingPropertyIsNotReplacedAndLogged() throws RepositoryException { ctx.warn("Property \"bar\" was expected not to exist at /foo, but exists with value \"old-value\" and was going to be created with value \"newValue\"."); final MockContent node = new MockContent("foo"); node.addNodeData("bar", "old-value"); final PropertyValuesTask pvd = new DummyPropertyValuesDelta(); replay(ctx); pvd.newProperty(ctx, node, "bar", "newValue"); verify(ctx); } |
### Question:
PartialBootstrapTask extends AbstractTask { protected String getOutputResourceName(final String resource, final String itemPath) { String inputResourceName = BootstrapUtil.getFilenameFromResource(resource, ".xml"); String tmpitemPath = itemPath.replace("/", "."); tmpitemPath = StringUtils.removeStart(tmpitemPath, "."); tmpitemPath = StringUtils.substringAfter(tmpitemPath, "."); String outputResourceName = inputResourceName + "." + tmpitemPath; if(StringUtils.isNotEmpty(targetResource)) { outputResourceName = targetResource; } return outputResourceName; } PartialBootstrapTask(String name, String description, String resource, String itemPath); PartialBootstrapTask(String name, String description, String resource, String itemPath, String targetResource); PartialBootstrapTask(String name, String description, String resource, String itemPath, String targetResource, int importUUIDBehavior); PartialBootstrapTask(String name, String description, String resource, String itemPath, int importUUIDBehavior); @Override void execute(InstallContext ctx); }### Answer:
@Test public void testGetOutputResourceName() throws Exception { PartialBootstrapTask task = new PartialBootstrapTask("", "", "/mgnl-bootstrap/form/config.modules.form.dialogs.form.xml", "/form/tabConfirmEmail/confirmContentType"); String outputResourceName = task.getOutputResourceName(task.getResource(), task.getItemPath()); assertEquals("config.modules.form.dialogs.form.tabConfirmEmail.confirmContentType", outputResourceName); task = new PartialBootstrapTask("", "", "/mgnl-bootstrap/form/config.modules.form..baz.dialogs.form.xml", "/form/tabConfirmEmail/confirmContentType.qux"); outputResourceName = task.getOutputResourceName(task.getResource(), task.getItemPath()); assertEquals("config.modules.form..baz.dialogs.form.tabConfirmEmail.confirmContentType..qux", outputResourceName); } |
### Question:
ModuleManagerWebUI implements ModuleManagerUI { protected void performInstallOrUpdate() { final Runnable runnable = new Runnable() { @Override public void run() { try { moduleManager.performInstallOrUpdate(); } catch (Throwable e) { log.error("Could not perform installation: " + e.getMessage(), e); moduleManager.getInstallContext().error("Could not perform installation: " + e.getMessage(), e); } } }; new Thread(runnable).start(); } ModuleManagerWebUI(ModuleManager moduleManager); @Override void onStartup(); @Override boolean execute(Writer out, String command); @Override void renderTempPage(Writer out); static final String INSTALLER_PATH; }### Answer:
@Test public void testModuleManagementExceptionsArePropagatedEvenThoughTheUpdateIsRunningInASeparateThread() throws ModuleManagementException, InterruptedException { final InstallContextImpl ctx = new InstallContextImpl(new ModuleRegistryImpl()); final ModuleManager moduleManager = createStrictMock(ModuleManager.class); moduleManager.performInstallOrUpdate(); expectLastCall().andThrow(new IllegalStateException("boo!")); expect(moduleManager.getInstallContext()).andReturn(ctx); replay(moduleManager); final ModuleManagerWebUI ui = new ModuleManagerWebUI(moduleManager); ui.performInstallOrUpdate(); Thread.sleep(1000); verify(moduleManager); assertEquals(1, ctx.getMessages().size()); final List messagesForNoModule = (ctx.getMessages().get("General messages")); assertEquals(1, messagesForNoModule.size()); final InstallContext.Message msg = (InstallContext.Message) messagesForNoModule.get(0); assertEquals("Could not perform installation: boo!", msg.getMessage()); assertEquals(InstallContext.MessagePriority.error, msg.getPriority()); } |
### Question:
ModuleLifecycleContextImpl implements ModuleLifecycleContext { @Override public void registerModuleObservingComponent(String nodeName, ObservedManager component) { if (components.containsKey(nodeName)) { final Object currentObservedManager = components.get(nodeName); throw new IllegalStateException("ObservedManager " + currentObservedManager + " was already registered for nodes of name " + nodeName + ", " + component + " can't be registered."); } components.put(nodeName, component); } ModuleLifecycleContextImpl(); @Override void registerModuleObservingComponent(String nodeName, ObservedManager component); void start(Collection<Content> moduleNodes); @Override ModuleDefinition getCurrentModuleDefinition(); void setCurrentModuleDefinition(ModuleDefinition currentModuleDefinition); @Override int getPhase(); void setPhase(int phase); }### Answer:
@Test public void testCantRegisterAComponentIfNodeNameIsAlreadyForAnotherComponent() { final ModuleLifecycleContextImpl lifecycleCtx = new ModuleLifecycleContextImpl(); lifecycleCtx.registerModuleObservingComponent("foo", new DummyObservedManager1()); try { lifecycleCtx.registerModuleObservingComponent("foo", new DummyObservedManager2()); fail("should have failed"); } catch (IllegalStateException e) { assertEquals("ObservedManager DummyObservedManager1 was already registered for nodes of name foo, DummyObservedManager2 can't be registered.", e.getMessage()); } } |
### Question:
AbstractModuleVersionHandler implements ModuleVersionHandler { protected void register(Delta delta) { final Version v = delta.getVersion(); if (allDeltas.containsKey(v)) { throw new IllegalStateException("Version " + v + " was already registered in this ModuleVersionHandler."); } delta.getTasks().addAll(getDefaultUpdateTasks(v)); delta.getConditions().addAll(getDefaultUpdateConditions(v)); allDeltas.put(v, delta); } AbstractModuleVersionHandler(); @Override Version getCurrentlyInstalled(InstallContext ctx); @Override List<Delta> getDeltas(InstallContext installContext, Version from); @Override Delta getStartupDelta(InstallContext installContext); }### Answer:
@Test public void testCantRegisterMultipleDeltasForSameVersion() { final Delta d1 = DeltaBuilder.update(Version.parseVersion("1.0.0"), "", new NullTask("", "")); final Delta d2 = DeltaBuilder.update(Version.parseVersion("1.0.0"), "", new NullTask("", "")); final AbstractModuleVersionHandler versionHandler = newTestModuleVersionHandler(); versionHandler.register(d1); try { versionHandler.register(d2); fail("should have failed"); } catch (IllegalStateException e) { assertEquals("Version 1.0.0 was already registered in this ModuleVersionHandler.", e.getMessage()); } } |
### Question:
ModuleRegistryImpl implements ModuleRegistry { @Override public List<ModuleDefinition> getModuleDefinitions() { final List<ModuleDefinition> defs = new ArrayList<ModuleDefinition>(); for (ModuleEntry mod : entries.values()) { defs.add(mod.moduleDefinition); } return Collections.unmodifiableList(defs); } ModuleRegistryImpl(); @Override void registerModuleDefinition(String name, ModuleDefinition moduleDefinition); @Override void registerModuleInstance(String name, Object moduleInstance); @Override void registerModuleVersionHandler(String name, ModuleVersionHandler moduleVersionHandler); @Override boolean isModuleRegistered(String name); @Override ModuleDefinition getDefinition(String name); @Override Object getModuleInstance(String name); @Override T getModuleInstance(final Class<T> moduleClass); @Override ModuleVersionHandler getVersionHandler(String name); @Override Set<String> getModuleNames(); @Override List<ModuleDefinition> getModuleDefinitions(); }### Answer:
@Test public void testModuleDefinitionsAreListedInDependencyOrder() throws ModuleManagementException { final ModuleDefinition a = new ModuleDefinition("a", Version.parseVersion("1.0"), null, null); final ModuleDefinition b = new ModuleDefinition("b", Version.parseVersion("1.0"), null, null); final ModuleDefinition c = new ModuleDefinition("c", Version.parseVersion("1.0"), null, null); b.addDependency(new DependencyDefinition("a", "1.0", false)); c.addDependency(new DependencyDefinition("a", "1.0", false)); c.addDependency(new DependencyDefinition("b", "1.0", false)); final ModuleRegistryImpl moduleRegistry = new ModuleRegistryImpl(); final ModuleManagerImpl moduleManager = new ModuleManagerImpl(null, new FixedModuleDefinitionReader(c, b, a), moduleRegistry, new DependencyCheckerImpl(), null); moduleManager.loadDefinitions(); final List<ModuleDefinition> result = moduleRegistry.getModuleDefinitions(); assertEquals(3, result.size()); assertEquals("a", result.get(0).getName()); assertEquals("b", result.get(1).getName()); assertEquals("c", result.get(2).getName()); } |
### Question:
RenameACLNodesTask extends AbstractRepositoryTask { public RenameACLNodesTask() { super("Security", "Renames ACL nodes."); } RenameACLNodesTask(); }### Answer:
@Test public void testRenameACLNodesTask() throws Exception { Session session = MgnlContext.getSystemContext().getJCRSession(RepositoryConstants.USER_ROLES); Node roleNode = session.getRootNode().addNode("superuser", NodeTypes.Role.NAME); roleNode.addNode("acl_dms_dms", NodeTypes.ContentNode.NAME); roleNode.addNode("acl_website", NodeTypes.ContentNode.NAME); roleNode.addNode("something_else_completely", NodeTypes.ContentNode.NAME); InstallContext installContext = mock(InstallContext.class); when(installContext.getJCRSession(RepositoryConstants.USER_ROLES)).thenReturn(session); RenameACLNodesTask task = new RenameACLNodesTask(); task.execute(installContext); session.getNode("/superuser/acl_dms"); session.getNode("/superuser/acl_website"); session.getNode("/superuser/something_else_completely"); } |
### Question:
BasePatternVoter extends AbstractBoolVoter { public void init() { if(autoTrueValue){ if(!isInverse()){ setTrueValue(pattern.length()); } else{ setTrueValue(-pattern.length()); } } } void init(); @Override void setTrueValue(int positiveVoteValue); String getPattern(); void setPattern(String pattern); boolean isInverse(); void setInverse(boolean inverse); @Override String toString(); }### Answer:
@Test public void testInitWithoutPattern(){ BasePatternVoter voter = new BasePatternVoter() { @Override protected boolean boolVote(Object value) { return false; }}; voter.init(); } |
### Question:
ResponseContentTypeVoter extends AbstractBoolVoter { public void addAllowed(String contentType) { allowed.add(contentType); } List<String> getAllowed(); void setAllowed(List<String> allowed); void addAllowed(String contentType); List<String> getRejected(); void setRejected(List<String> rejected); void addRejected(String contentType); }### Answer:
@Test public void testVotesTrueIfContentTypeIsAllowed() { voter.addAllowed("text/html"); voter.addAllowed("application/x-javascript"); voter.addAllowed("text/plain"); expect(response.getContentType()).andReturn("application/x-javascript"); doTest(true); }
@Test public void testVotesFalseIfContentTypeIsNotInAllowedList() { voter.addAllowed("text/html"); voter.addAllowed("application/x-javascript"); voter.addAllowed("text/plain"); expect(response.getContentType()).andReturn("whatever"); doTest(false); }
@Test public void testVotesFalseIfResponseDoesNotHaveAContentTypeSetYetEvenIfNoRejectedAreConfigured() { voter.addAllowed("text/html"); voter.addAllowed("application/x-javascript"); voter.addAllowed("text/plain"); expect(response.getContentType()).andReturn(null); doTest(false); }
@Test public void testIgnoresCharsetInContentType2() { voter.addAllowed("text/html"); voter.addAllowed("application/x-javascript"); voter.addAllowed("text/plain"); expect(response.getContentType()).andReturn("image/jpeg;charset=UTF-8"); doTest(false); } |
### Question:
ResponseContentTypeVoter extends AbstractBoolVoter { public void addRejected(String contentType) { rejected.add(contentType); } List<String> getAllowed(); void setAllowed(List<String> allowed); void addAllowed(String contentType); List<String> getRejected(); void setRejected(List<String> rejected); void addRejected(String contentType); }### Answer:
@Test public void testVotesFalseIfContentTypeIsExplicitelyRejected() { voter.addRejected("image/gif"); voter.addRejected("image/jpeg"); voter.addRejected("application/octet-stream"); expect(response.getContentType()).andReturn("image/gif"); doTest(false); }
@Test public void testVotesTrueIfContentTypeIsNotRejected() { voter.addRejected("image/gif"); voter.addRejected("image/jpeg"); voter.addRejected("application/octet-stream"); expect(response.getContentType()).andReturn("text/plain"); doTest(true); }
@Test public void testVotesFalseIfResponseDoesNotHaveAContentTypeSetYetEvenIfNoAllowedAreConfigured() { voter.addRejected("text/html"); voter.addRejected("application/x-javascript"); voter.addRejected("text/plain"); expect(response.getContentType()).andReturn(null); doTest(false); } |
### Question:
URIPatternVoter extends BasePatternVoter { @Override public void setPattern(String pattern) { super.setPattern(pattern); this.pattern = new SimpleUrlPattern(pattern); } @Override void setPattern(String pattern); }### Answer:
@Test public void testVotesTrueOnMatchingWildcardPattern() { URIPatternVoter voter = new URIPatternVoter(); voter.setPattern("/foo/bar*"); assertEquals(1, voter.vote("/foo/bar/zed")); }
@Test public void testVotesFalseOnNonMatchingWildcardPattern() { URIPatternVoter voter = new URIPatternVoter(); voter.setPattern("/foo/bar*"); assertEquals(0, voter.vote("/abc/xyz")); } |
### Question:
FreemarkerHelper { public void render(String templatePath, Object root, Writer out) throws TemplateException, IOException { render(templatePath, null, null, root, out); } FreemarkerHelper(); FreemarkerHelper(final FreemarkerConfig freemarkerConfig); static FreemarkerHelper getInstance(); void resetObjectWrapper(); void render(String templatePath, Object root, Writer out); void render(String templatePath, Locale locale, String i18nBasename, Object root, Writer out); void render(Reader template, Object root, Writer out); }### Answer:
@Test public void testContextPathIsNotAddedWithNotWebContext() throws IOException, TemplateException { tplLoader.putTemplate("pouet", ":${contextPath}:"); final Context context = createStrictMock(Context.class); expect(context.getLocale()).andReturn(Locale.US); replay(context); MgnlContext.setInstance(context); final StringWriter out = new StringWriter(); try { fmHelper.render("pouet", new HashMap(), out); fail("should have failed"); } catch (InvalidReferenceException e) { assertEquals("Expression contextPath is undefined on line 1, column 4 in pouet.", e.getMessage()); } verify(context); } |
### Question:
EmailNotificationSender implements NotificationSender { @Override public NotificationMedium getNotificationMedium() { return EMAIL; } @Override NotificationMedium getNotificationMedium(); @Override ServiceResult<Notification> sendNotification(Notification notification); @Override @Transactional(propagation = Propagation.MANDATORY) ServiceResult<Notification> sendNotificationWithFlush(Notification notification); }### Answer:
@Test public void testGetNotificationMedium() { assertEquals(EMAIL, notificationSender.getNotificationMedium()); } |
### Question:
InterviewApplicationFeedbackServiceImpl implements InterviewApplicationFeedbackService { @Override @Transactional(readOnly = true) public ServiceResult<FileEntryResource> findFeedback(long applicationId) { return findAssignmentByApplicationId(applicationId).andOnSuccess(interviewAssignment -> ofNullable(interviewAssignment.getMessage()) .map(InterviewAssignmentMessageOutcome::getFeedback) .map(FileEntry::getId) .map(fileEntryService::findOne) .orElse(ServiceResult.serviceSuccess(null))); } @Override ServiceResult<Void> uploadFeedback(String contentType, String contentLength, String originalFilename, long applicationId, HttpServletRequest request); @Override ServiceResult<Void> deleteFeedback(long applicationId); @Override @Transactional(readOnly = true) ServiceResult<FileAndContents> downloadFeedback(long applicationId); @Override @Transactional(readOnly = true) ServiceResult<FileEntryResource> findFeedback(long applicationId); }### Answer:
@Test public void findFeedback() throws Exception { long applicationId = 1L; FileEntry fileEntry = newFileEntry().build(); InterviewAssignment interviewAssignment = newInterviewAssignment(). withMessage(newInterviewAssignmentMessageOutcome() .withFeedback(fileEntry) .build() ).build(); FileEntryResource fileEntryResource = newFileEntryResource().build(); when(interviewAssignmentRepositoryMock.findOneByTargetId(applicationId)).thenReturn(interviewAssignment); when(fileEntryServiceMock.findOne(fileEntry.getId())).thenReturn(serviceSuccess(fileEntryResource)); FileEntryResource response = service.findFeedback(applicationId).getSuccess(); assertEquals(fileEntryResource, response); } |
### Question:
InterviewApplicationFeedbackServiceImpl implements InterviewApplicationFeedbackService { @Override @Transactional(readOnly = true) public ServiceResult<FileAndContents> downloadFeedback(long applicationId) { return findAssignmentByApplicationId(applicationId).andOnSuccess(interviewAssignment -> fileEntryService.findOne(interviewAssignment.getMessage().getFeedback().getId()) .andOnSuccess(this::getFileAndContents)); } @Override ServiceResult<Void> uploadFeedback(String contentType, String contentLength, String originalFilename, long applicationId, HttpServletRequest request); @Override ServiceResult<Void> deleteFeedback(long applicationId); @Override @Transactional(readOnly = true) ServiceResult<FileAndContents> downloadFeedback(long applicationId); @Override @Transactional(readOnly = true) ServiceResult<FileEntryResource> findFeedback(long applicationId); }### Answer:
@Test public void downloadFeedback() throws Exception { final long applicationId = 1L; final long fileId = 2L; final FileEntry fileEntry = new FileEntry(fileId, "somefile.pdf", MediaType.APPLICATION_PDF, 1111L); InterviewAssignment interviewAssignment = newInterviewAssignment(). withMessage(newInterviewAssignmentMessageOutcome() .withFeedback(fileEntry) .build() ).build(); FileEntryResource fileEntryResource = new FileEntryResource(); fileEntryResource.setId(fileId); when(interviewAssignmentRepositoryMock.findOneByTargetId(applicationId)).thenReturn(interviewAssignment); when(fileEntryServiceMock.findOne(fileId)).thenReturn(serviceSuccess(fileEntryResource)); final Supplier<InputStream> contentSupplier = () -> null; when(fileServiceMock.getFileByFileEntryId(fileEntry.getId())).thenReturn(ServiceResult.serviceSuccess(contentSupplier)); FileAndContents fileAndContents = service.downloadFeedback(applicationId).getSuccess(); assertEquals(fileAndContents.getContentsSupplier(), contentSupplier); assertEquals(fileAndContents.getFileEntry(), fileEntryResource); } |
### Question:
InterviewAllocationServiceImpl implements InterviewAllocationService { @Override public ServiceResult<List<Long>> getUnallocatedApplicationIds(long competitionId, long assessorId) { return serviceSuccess(interviewRepository.findApplicationIdsNotAssignedToAssessor(competitionId, assessorId)); } @Override ServiceResult<InterviewAcceptedAssessorsPageResource> getInterviewAcceptedAssessors(long competitionId,
Pageable pageable); @Override ServiceResult<InterviewApplicationPageResource> getUnallocatedApplications(long competitionId, long assessorUserId, Pageable pageable); @Override ServiceResult<InterviewApplicationPageResource> getAllocatedApplications(long competitionId, long assessorUserId, Pageable pageable); @Override ServiceResult<List<InterviewResource>> getAllocatedApplicationsByAssessorId(long competitionId, long assessorUserId); @Override ServiceResult<List<InterviewApplicationResource>> getUnallocatedApplicationsById(List<Long> applicationIds); @Override ServiceResult<List<Long>> getUnallocatedApplicationIds(long competitionId, long assessorId); @Override ServiceResult<AssessorInvitesToSendResource> getInviteToSend(long competitionId, long assessorId); @Override @Transactional ServiceResult<Void> unallocateApplication(long assessorId, long applicationId); @Override @Transactional ServiceResult<Void> notifyAllocation(InterviewNotifyAllocationResource interviewNotifyAllocationResource); }### Answer:
@Test public void getUnallocatedApplicationIds() { long competitionId = 1L; long userId = 2L; List<Long> ids = asList(4L, 5L); when(interviewRepositoryMock.findApplicationIdsNotAssignedToAssessor( competitionId, userId )).thenReturn(ids); ServiceResult<List<Long>> result = service.getUnallocatedApplicationIds(competitionId, userId); verify(interviewRepositoryMock) .findApplicationIdsNotAssignedToAssessor(competitionId, userId); assertTrue(result.isSuccess()); assertEquals(result.getSuccess(), ids); } |
### Question:
InterviewAllocationServiceImpl implements InterviewAllocationService { @Override public ServiceResult<List<InterviewApplicationResource>> getUnallocatedApplicationsById(List<Long> applicationIds) { return serviceSuccess(interviewRepository.findAllNotified(applicationIds)); } @Override ServiceResult<InterviewAcceptedAssessorsPageResource> getInterviewAcceptedAssessors(long competitionId,
Pageable pageable); @Override ServiceResult<InterviewApplicationPageResource> getUnallocatedApplications(long competitionId, long assessorUserId, Pageable pageable); @Override ServiceResult<InterviewApplicationPageResource> getAllocatedApplications(long competitionId, long assessorUserId, Pageable pageable); @Override ServiceResult<List<InterviewResource>> getAllocatedApplicationsByAssessorId(long competitionId, long assessorUserId); @Override ServiceResult<List<InterviewApplicationResource>> getUnallocatedApplicationsById(List<Long> applicationIds); @Override ServiceResult<List<Long>> getUnallocatedApplicationIds(long competitionId, long assessorId); @Override ServiceResult<AssessorInvitesToSendResource> getInviteToSend(long competitionId, long assessorId); @Override @Transactional ServiceResult<Void> unallocateApplication(long assessorId, long applicationId); @Override @Transactional ServiceResult<Void> notifyAllocation(InterviewNotifyAllocationResource interviewNotifyAllocationResource); }### Answer:
@Test public void getUnallocatedApplicationsById() { Long[] applicationIds = {1L, 2L}; List<InterviewApplicationResource> expectedInterviewApplications = newInterviewApplicationResource().build(2); when(interviewRepositoryMock.findAllNotified(asList(applicationIds))).thenReturn(expectedInterviewApplications); List<InterviewApplicationResource> actualInterviewApplications = service.getUnallocatedApplicationsById(asList(applicationIds)).getSuccess(); assertEquals(expectedInterviewApplications, actualInterviewApplications); verify(interviewRepositoryMock, only()).findAllNotified(asList(applicationIds)); } |
### Question:
InterviewResponseServiceImpl implements InterviewResponseService { @Override @Transactional(readOnly = true) public ServiceResult<FileEntryResource> findResponse(long applicationId) { return findAssignmentByApplicationId(applicationId).andOnSuccess(interviewAssignment -> ofNullable(interviewAssignment.getResponse()) .map(InterviewAssignmentResponseOutcome::getFileResponse) .map(FileEntry::getId) .map(fileId -> fileEntryService.findOne(fileId)) .orElse(serviceSuccess(null))); } @Override ServiceResult<Void> uploadResponse(String contentType, String contentLength, String originalFilename, long applicationId, HttpServletRequest request); @Override ServiceResult<Void> deleteResponse(long applicationId); @Override @Transactional(readOnly = true) ServiceResult<FileAndContents> downloadResponse(long applicationId); @Override @Transactional(readOnly = true) ServiceResult<FileEntryResource> findResponse(long applicationId); }### Answer:
@Test public void findResponse() throws Exception { long applicationId = 1L; FileEntry fileEntry = newFileEntry().build(); InterviewAssignment interviewAssignment = newInterviewAssignment(). withResponse(newInterviewAssignmentResponseOutcome() .withFileResponse(fileEntry) .build() ).build(); FileEntryResource fileEntryResource = newFileEntryResource().build(); when(interviewAssignmentRepositoryMock.findOneByTargetId(applicationId)).thenReturn(interviewAssignment); when(fileEntryServiceMock.findOne(fileEntry.getId())).thenReturn(serviceSuccess(fileEntryResource)); FileEntryResource response = service.findResponse(applicationId).getSuccess(); assertEquals(fileEntryResource, response); } |
### Question:
InterviewResponseServiceImpl implements InterviewResponseService { @Override @Transactional(readOnly = true) public ServiceResult<FileAndContents> downloadResponse(long applicationId) { return findAssignmentByApplicationId(applicationId).andOnSuccess(interviewAssignment -> fileEntryService.findOne(interviewAssignment.getResponse().getFileResponse().getId()) .andOnSuccess(this::getFileAndContents)); } @Override ServiceResult<Void> uploadResponse(String contentType, String contentLength, String originalFilename, long applicationId, HttpServletRequest request); @Override ServiceResult<Void> deleteResponse(long applicationId); @Override @Transactional(readOnly = true) ServiceResult<FileAndContents> downloadResponse(long applicationId); @Override @Transactional(readOnly = true) ServiceResult<FileEntryResource> findResponse(long applicationId); }### Answer:
@Test public void downloadResponse() throws Exception { final long applicationId = 1L; final long fileId = 2L; final FileEntry fileEntry = new FileEntry(fileId, "somefile.pdf", MediaType.APPLICATION_PDF, 1111L); InterviewAssignment interviewAssignment = newInterviewAssignment(). withResponse(newInterviewAssignmentResponseOutcome() .withFileResponse(fileEntry) .build() ).build(); FileEntryResource fileEntryResource = new FileEntryResource(); fileEntryResource.setId(fileId); when(interviewAssignmentRepositoryMock.findOneByTargetId(applicationId)).thenReturn(interviewAssignment); when(fileEntryServiceMock.findOne(fileId)).thenReturn(serviceSuccess(fileEntryResource)); final Supplier<InputStream> contentSupplier = () -> null; when(fileServiceMock.getFileByFileEntryId(fileEntry.getId())).thenReturn(ServiceResult.serviceSuccess(contentSupplier)); FileAndContents fileAndContents = service.downloadResponse(applicationId).getSuccess(); assertEquals(fileAndContents.getContentsSupplier(), contentSupplier); assertEquals(fileAndContents.getFileEntry(), fileEntryResource); } |
### Question:
InterviewResponseServiceImpl implements InterviewResponseService { @Override public ServiceResult<Void> deleteResponse(long applicationId) { return findAssignmentByApplicationId(applicationId).andOnSuccessReturnVoid(interviewAssignment -> interviewAssignmentWorkflowHandler.withdrawResponse(interviewAssignment) ); } @Override ServiceResult<Void> uploadResponse(String contentType, String contentLength, String originalFilename, long applicationId, HttpServletRequest request); @Override ServiceResult<Void> deleteResponse(long applicationId); @Override @Transactional(readOnly = true) ServiceResult<FileAndContents> downloadResponse(long applicationId); @Override @Transactional(readOnly = true) ServiceResult<FileEntryResource> findResponse(long applicationId); }### Answer:
@Test public void deleteResponse() throws Exception { final long applicationId = 1L; InterviewAssignment interviewAssignment = newInterviewAssignment() .build(); when(interviewAssignmentRepositoryMock.findOneByTargetId(applicationId)).thenReturn(interviewAssignment); when(interviewAssignmentWorkflowHandler.withdrawResponse(interviewAssignment)).thenReturn(true); ServiceResult<Void> response = service.deleteResponse(applicationId); assertTrue(response.isSuccess()); verify(interviewAssignmentWorkflowHandler).withdrawResponse(interviewAssignment); } |
### Question:
InterviewAssignmentServiceImpl implements InterviewAssignmentService { @Override @Transactional(readOnly = true) public ServiceResult<List<Long>> getAvailableApplicationIds(long competitionId) { return serviceSuccess( simpleMap( applicationRepository.findSubmittedApplicationsNotOnInterviewPanel(competitionId), Application::getId ) ); } @Override @Transactional(readOnly = true) ServiceResult<AvailableApplicationPageResource> getAvailableApplications(long competitionId, Pageable pageable); @Override @Transactional(readOnly = true) ServiceResult<InterviewAssignmentStagedApplicationPageResource> getStagedApplications(long competitionId, Pageable pageable); @Override @Transactional(readOnly = true) ServiceResult<InterviewAssignmentApplicationPageResource> getAssignedApplications(long competitionId, Pageable pageable); @Override @Transactional(readOnly = true) ServiceResult<List<Long>> getAvailableApplicationIds(long competitionId); @Override ServiceResult<Void> assignApplications(List<StagedApplicationResource> stagedInvites); @Override ServiceResult<Void> unstageApplication(long applicationId); @Override ServiceResult<Void> unstageApplications(long competitionId); @Override @Transactional(readOnly = true) ServiceResult<Boolean> isApplicationAssigned(long applicationId); }### Answer:
@Test public void getAvailableApplicationIds() { when(applicationRepositoryMock.findSubmittedApplicationsNotOnInterviewPanel(COMPETITION_ID)) .thenReturn(EXPECTED_AVAILABLE_APPLICATIONS); List<Long> availableApplicationIds = service.getAvailableApplicationIds(COMPETITION_ID).getSuccess(); assertEquals(simpleMap(EXPECTED_AVAILABLE_APPLICATIONS, Application::getId), availableApplicationIds); verify(applicationRepositoryMock, only()).findSubmittedApplicationsNotOnInterviewPanel(COMPETITION_ID); } |
### Question:
InterviewAssignmentServiceImpl implements InterviewAssignmentService { @Override public ServiceResult<Void> unstageApplication(long applicationId) { interviewAssignmentRepository.deleteByTargetIdAndActivityState(applicationId, CREATED); return serviceSuccess(); } @Override @Transactional(readOnly = true) ServiceResult<AvailableApplicationPageResource> getAvailableApplications(long competitionId, Pageable pageable); @Override @Transactional(readOnly = true) ServiceResult<InterviewAssignmentStagedApplicationPageResource> getStagedApplications(long competitionId, Pageable pageable); @Override @Transactional(readOnly = true) ServiceResult<InterviewAssignmentApplicationPageResource> getAssignedApplications(long competitionId, Pageable pageable); @Override @Transactional(readOnly = true) ServiceResult<List<Long>> getAvailableApplicationIds(long competitionId); @Override ServiceResult<Void> assignApplications(List<StagedApplicationResource> stagedInvites); @Override ServiceResult<Void> unstageApplication(long applicationId); @Override ServiceResult<Void> unstageApplications(long competitionId); @Override @Transactional(readOnly = true) ServiceResult<Boolean> isApplicationAssigned(long applicationId); }### Answer:
@Test public void unstageApplication() { long applicationId = 1L; ServiceResult<Void> result = service.unstageApplication(applicationId); assertTrue(result.isSuccess()); verify(interviewAssignmentRepositoryMock).deleteByTargetIdAndActivityState(applicationId, InterviewAssignmentState.CREATED); } |
### Question:
InterviewAssignmentServiceImpl implements InterviewAssignmentService { @Override public ServiceResult<Void> unstageApplications(long competitionId) { interviewAssignmentRepository.deleteByTargetCompetitionIdAndActivityState(competitionId, CREATED); return serviceSuccess(); } @Override @Transactional(readOnly = true) ServiceResult<AvailableApplicationPageResource> getAvailableApplications(long competitionId, Pageable pageable); @Override @Transactional(readOnly = true) ServiceResult<InterviewAssignmentStagedApplicationPageResource> getStagedApplications(long competitionId, Pageable pageable); @Override @Transactional(readOnly = true) ServiceResult<InterviewAssignmentApplicationPageResource> getAssignedApplications(long competitionId, Pageable pageable); @Override @Transactional(readOnly = true) ServiceResult<List<Long>> getAvailableApplicationIds(long competitionId); @Override ServiceResult<Void> assignApplications(List<StagedApplicationResource> stagedInvites); @Override ServiceResult<Void> unstageApplication(long applicationId); @Override ServiceResult<Void> unstageApplications(long competitionId); @Override @Transactional(readOnly = true) ServiceResult<Boolean> isApplicationAssigned(long applicationId); }### Answer:
@Test public void unstageApplications() { long competitionId = 1L; ServiceResult<Void> result = service.unstageApplications(1L); assertTrue(result.isSuccess()); verify(interviewAssignmentRepositoryMock).deleteByTargetCompetitionIdAndActivityState(competitionId, InterviewAssignmentState.CREATED); } |
### Question:
InterviewAssignmentServiceImpl implements InterviewAssignmentService { @Override @Transactional(readOnly = true) public ServiceResult<Boolean> isApplicationAssigned(long applicationId) { return serviceSuccess(interviewAssignmentRepository.existsByTargetIdAndActivityStateIn(applicationId, asList(AWAITING_FEEDBACK_RESPONSE, SUBMITTED_FEEDBACK_RESPONSE))); } @Override @Transactional(readOnly = true) ServiceResult<AvailableApplicationPageResource> getAvailableApplications(long competitionId, Pageable pageable); @Override @Transactional(readOnly = true) ServiceResult<InterviewAssignmentStagedApplicationPageResource> getStagedApplications(long competitionId, Pageable pageable); @Override @Transactional(readOnly = true) ServiceResult<InterviewAssignmentApplicationPageResource> getAssignedApplications(long competitionId, Pageable pageable); @Override @Transactional(readOnly = true) ServiceResult<List<Long>> getAvailableApplicationIds(long competitionId); @Override ServiceResult<Void> assignApplications(List<StagedApplicationResource> stagedInvites); @Override ServiceResult<Void> unstageApplication(long applicationId); @Override ServiceResult<Void> unstageApplications(long competitionId); @Override @Transactional(readOnly = true) ServiceResult<Boolean> isApplicationAssigned(long applicationId); }### Answer:
@Test public void isApplicationAssigned() { long applicationId = 1L; when(interviewAssignmentRepositoryMock.existsByTargetIdAndActivityStateIn(applicationId, asList(AWAITING_FEEDBACK_RESPONSE, SUBMITTED_FEEDBACK_RESPONSE))) .thenReturn(true); ServiceResult<Boolean> result = service.isApplicationAssigned(applicationId); assertTrue(result.getSuccess()); } |
### Question:
InterviewApplicationInviteServiceImpl implements InterviewApplicationInviteService { @Override public ServiceResult<ApplicantInterviewInviteResource> getEmailTemplate() { NotificationTarget notificationTarget = new UserNotificationTarget("", ""); return renderer.renderTemplate(systemNotificationSource, notificationTarget, PREVIEW_TEMPLATES_PATH + "invite_applicants_to_interview_panel_text.txt", Collections.emptyMap()).andOnSuccessReturn(content -> new ApplicantInterviewInviteResource(content)); } @Override ServiceResult<ApplicantInterviewInviteResource> getEmailTemplate(); @Override ServiceResult<Void> sendInvites(long competitionId, AssessorInviteSendResource assessorInviteSendResource); @Override ServiceResult<InterviewApplicationSentInviteResource> getSentInvite(long applicationId); @Override ServiceResult<Void> resendInvite(long applicationId, AssessorInviteSendResource assessorInviteSendResource); }### Answer:
@Test public void getEmailTemplate() { when(notificationTemplateRendererMock.renderTemplate(eq(systemNotificationSourceMock), any(NotificationTarget.class), eq(PREVIEW_TEMPLATES_PATH + "invite_applicants_to_interview_panel_text.txt"), any(Map.class))).thenReturn(serviceSuccess("Content")); ServiceResult<ApplicantInterviewInviteResource> result = service.getEmailTemplate(); assertTrue(result.isSuccess()); assertEquals(result.getSuccess().getContent(),"Content"); } |
### Question:
InterviewApplicationInviteServiceImpl implements InterviewApplicationInviteService { @Override public ServiceResult<InterviewApplicationSentInviteResource> getSentInvite(long applicationId) { InterviewAssignment assignment = interviewAssignmentRepository.findOneByTargetId(applicationId); return ofNullable(assignment.getMessage()) .map(message -> serviceSuccess( new InterviewApplicationSentInviteResource(message.getSubject(), message.getMessage(), message.getCreatedOn()) ) ) .orElse(serviceFailure(GENERAL_NOT_FOUND)); } @Override ServiceResult<ApplicantInterviewInviteResource> getEmailTemplate(); @Override ServiceResult<Void> sendInvites(long competitionId, AssessorInviteSendResource assessorInviteSendResource); @Override ServiceResult<InterviewApplicationSentInviteResource> getSentInvite(long applicationId); @Override ServiceResult<Void> resendInvite(long applicationId, AssessorInviteSendResource assessorInviteSendResource); }### Answer:
@Test public void getSentInvite() { long applicationId = 1L; String subject = "subject"; String content = "content"; ZonedDateTime assigned = ZonedDateTime.now(); InterviewApplicationSentInviteResource expected = newInterviewApplicationSentInviteResource() .withContent(content) .withSubject(subject) .withAssigned(assigned) .build(); InterviewAssignmentMessageOutcome message = newInterviewAssignmentMessageOutcome() .withSubject(subject) .withMessage(content) .withCreatedOn(assigned) .build(); InterviewAssignment interviewAssignment = newInterviewAssignment() .withMessage(message) .build(); when(interviewAssignmentRepositoryMock.findOneByTargetId(applicationId)).thenReturn(interviewAssignment); ServiceResult<InterviewApplicationSentInviteResource> result = service.getSentInvite(applicationId); assertTrue(result.isSuccess()); assertEquals(expected, result.getSuccess()); } |
### Question:
CompetitionSetupInnovationLeadController { @GetMapping("/{competitionId}/innovation-leads") public RestResult<List<UserResource>> findAvailableInnovationLeadsNotAssignedToCompetition(@PathVariable("competitionId") final long competitionId) { return competitionSetupInnovationLeadService.findInnovationLeads(competitionId).toGetResponse(); } @GetMapping("/{competitionId}/innovation-leads") RestResult<List<UserResource>> findAvailableInnovationLeadsNotAssignedToCompetition(@PathVariable("competitionId") final long competitionId); @GetMapping("/{competitionId}/innovation-leads/find-added") RestResult<List<UserResource>> findInnovationLeadsAddedToCompetition(@PathVariable("competitionId") final long competitionId); @PostMapping("/{competitionId}/add-innovation-lead/{innovationLeadUserId}") RestResult<Void> addInnovationLead(@PathVariable("competitionId") final long competitionId,
@PathVariable("innovationLeadUserId") final long innovationLeadUserId); @PostMapping("/{competitionId}/remove-innovation-lead/{innovationLeadUserId}") RestResult<Void> removeInnovationLead(@PathVariable("competitionId") final long competitionId,
@PathVariable("innovationLeadUserId") final long innovationLeadUserId); }### Answer:
@Test public void findAvailableInnovationLeadsNotAssignedToCompetition() throws Exception { final long competitionId = 1L; List<UserResource> innovationLeads = new ArrayList<>(); when(competitionSetupInnovationLeadService.findInnovationLeads(competitionId)).thenReturn(serviceSuccess(innovationLeads)); mockMvc.perform(get("/competition/setup/{id}/innovation-leads", competitionId)) .andExpect(status().isOk()) .andExpect(content().json(toJson(innovationLeads))); verify(competitionSetupInnovationLeadService).findInnovationLeads(competitionId); } |
### Question:
CompetitionSetupInnovationLeadController { @GetMapping("/{competitionId}/innovation-leads/find-added") public RestResult<List<UserResource>> findInnovationLeadsAddedToCompetition(@PathVariable("competitionId") final long competitionId) { return competitionSetupInnovationLeadService.findAddedInnovationLeads(competitionId).toGetResponse(); } @GetMapping("/{competitionId}/innovation-leads") RestResult<List<UserResource>> findAvailableInnovationLeadsNotAssignedToCompetition(@PathVariable("competitionId") final long competitionId); @GetMapping("/{competitionId}/innovation-leads/find-added") RestResult<List<UserResource>> findInnovationLeadsAddedToCompetition(@PathVariable("competitionId") final long competitionId); @PostMapping("/{competitionId}/add-innovation-lead/{innovationLeadUserId}") RestResult<Void> addInnovationLead(@PathVariable("competitionId") final long competitionId,
@PathVariable("innovationLeadUserId") final long innovationLeadUserId); @PostMapping("/{competitionId}/remove-innovation-lead/{innovationLeadUserId}") RestResult<Void> removeInnovationLead(@PathVariable("competitionId") final long competitionId,
@PathVariable("innovationLeadUserId") final long innovationLeadUserId); }### Answer:
@Test public void findInnovationLeadsAddedToCompetition() throws Exception { final long competitionId = 1L; List<UserResource> innovationLeads = new ArrayList<>(); when(competitionSetupInnovationLeadService.findAddedInnovationLeads(competitionId)).thenReturn(serviceSuccess(innovationLeads)); mockMvc.perform(get("/competition/setup/{id}/innovation-leads/find-added", competitionId)) .andExpect(status().isOk()) .andExpect(content().json(toJson(innovationLeads))); verify(competitionSetupInnovationLeadService, only()).findAddedInnovationLeads(competitionId); } |
### Question:
CompetitionSetupInnovationLeadController { @PostMapping("/{competitionId}/add-innovation-lead/{innovationLeadUserId}") public RestResult<Void> addInnovationLead(@PathVariable("competitionId") final long competitionId, @PathVariable("innovationLeadUserId") final long innovationLeadUserId) { return competitionSetupInnovationLeadService.addInnovationLead(competitionId, innovationLeadUserId).toPostResponse(); } @GetMapping("/{competitionId}/innovation-leads") RestResult<List<UserResource>> findAvailableInnovationLeadsNotAssignedToCompetition(@PathVariable("competitionId") final long competitionId); @GetMapping("/{competitionId}/innovation-leads/find-added") RestResult<List<UserResource>> findInnovationLeadsAddedToCompetition(@PathVariable("competitionId") final long competitionId); @PostMapping("/{competitionId}/add-innovation-lead/{innovationLeadUserId}") RestResult<Void> addInnovationLead(@PathVariable("competitionId") final long competitionId,
@PathVariable("innovationLeadUserId") final long innovationLeadUserId); @PostMapping("/{competitionId}/remove-innovation-lead/{innovationLeadUserId}") RestResult<Void> removeInnovationLead(@PathVariable("competitionId") final long competitionId,
@PathVariable("innovationLeadUserId") final long innovationLeadUserId); }### Answer:
@Test public void addInnovationLead() throws Exception { final long competitionId = 1L; final long innovationLeadUserId = 2L; when(competitionSetupInnovationLeadService.addInnovationLead(competitionId, innovationLeadUserId)).thenReturn(serviceSuccess()); mockMvc.perform(post("/competition/setup/{id}/add-innovation-lead/{innovationLeadUserId}", competitionId, innovationLeadUserId)) .andExpect(status().isOk()); verify(competitionSetupInnovationLeadService, only()).addInnovationLead(competitionId, innovationLeadUserId); } |
### Question:
CompetitionSetupInnovationLeadController { @PostMapping("/{competitionId}/remove-innovation-lead/{innovationLeadUserId}") public RestResult<Void> removeInnovationLead(@PathVariable("competitionId") final long competitionId, @PathVariable("innovationLeadUserId") final long innovationLeadUserId) { return competitionSetupInnovationLeadService.removeInnovationLead(competitionId, innovationLeadUserId).toPostResponse(); } @GetMapping("/{competitionId}/innovation-leads") RestResult<List<UserResource>> findAvailableInnovationLeadsNotAssignedToCompetition(@PathVariable("competitionId") final long competitionId); @GetMapping("/{competitionId}/innovation-leads/find-added") RestResult<List<UserResource>> findInnovationLeadsAddedToCompetition(@PathVariable("competitionId") final long competitionId); @PostMapping("/{competitionId}/add-innovation-lead/{innovationLeadUserId}") RestResult<Void> addInnovationLead(@PathVariable("competitionId") final long competitionId,
@PathVariable("innovationLeadUserId") final long innovationLeadUserId); @PostMapping("/{competitionId}/remove-innovation-lead/{innovationLeadUserId}") RestResult<Void> removeInnovationLead(@PathVariable("competitionId") final long competitionId,
@PathVariable("innovationLeadUserId") final long innovationLeadUserId); }### Answer:
@Test public void removeInnovationLead() throws Exception { final long competitionId = 1L; final long innovationLeadUserId = 2L; when(competitionSetupInnovationLeadService.removeInnovationLead(competitionId, innovationLeadUserId)).thenReturn(serviceSuccess()); mockMvc.perform(post("/competition/setup/{id}/remove-innovation-lead/{innovationLeadUserId}", competitionId, innovationLeadUserId)) .andExpect(status().isOk()); verify(competitionSetupInnovationLeadService).removeInnovationLead(competitionId, innovationLeadUserId); } |
### Question:
CompetitionSetupPostAwardServiceController { @PostMapping("/{competitionId}/post-award-service/{postAwardService}") public RestResult<Void> configurePostAwardService(@PathVariable("competitionId") final long competitionId, @PathVariable("postAwardService") final PostAwardService postAwardService) { return competitionSetupPostAwardServiceService.configurePostAwardService(competitionId, postAwardService).toPostResponse(); } @GetMapping("/{competitionId}/post-award-service") RestResult<CompetitionPostAwardServiceResource> postAwardService(@PathVariable("competitionId") final long competitionId); @PostMapping("/{competitionId}/post-award-service/{postAwardService}") RestResult<Void> configurePostAwardService(@PathVariable("competitionId") final long competitionId,
@PathVariable("postAwardService") final PostAwardService postAwardService); }### Answer:
@Test public void configurePostAwardService() throws Exception { final long competitionId = 1L; final PostAwardService postAwardService = PostAwardService.CONNECT; when(competitionSetupPostAwardServiceService.configurePostAwardService(competitionId, postAwardService)).thenReturn(serviceSuccess()); mockMvc.perform(post("/competition/setup/{id}/post-award-service/{innovationLeadUserId}", competitionId, postAwardService.name())) .andExpect(status().isOk()); verify(competitionSetupPostAwardServiceService, only()).configurePostAwardService(competitionId, postAwardService); } |
### Question:
CompetitionSetupFinanceServiceImpl extends BaseTransactionalService implements
CompetitionSetupFinanceService { @Override @Transactional public ServiceResult<Void> save(CompetitionSetupFinanceResource compSetupFinanceRes) { return getCompetition(compSetupFinanceRes.getCompetitionId()).andOnSuccess(competition -> { competition.setApplicationFinanceType(compSetupFinanceRes.getApplicationFinanceType()); competition.setIncludeJesForm(compSetupFinanceRes.getIncludeJesForm()); competition.setIncludeProjectGrowthTable(compSetupFinanceRes.getIncludeGrowthTable()); competition.setIncludeYourOrganisationSection(compSetupFinanceRes.getIncludeYourOrganisationSection()); return serviceSuccess(); }); } @Override @Transactional ServiceResult<Void> save(CompetitionSetupFinanceResource compSetupFinanceRes); @Override ServiceResult<CompetitionSetupFinanceResource> getForCompetition(long competitionId); }### Answer:
@Test public void save() { long competitionId = 1L; boolean isIncludeGrowthTable = false; boolean isIncludeYourOrganisationSection = false; boolean includeJesForm = true; CompetitionSetupFinanceResource compSetupFinanceRes = newCompetitionSetupFinanceResource() .withCompetitionId(competitionId) .withIncludeGrowthTable(isIncludeGrowthTable) .withIncludeJesForm(includeJesForm) .withIncludeYourOrganisationSection(isIncludeYourOrganisationSection) .withApplicationFinanceType(STANDARD) .build(); Competition c = newCompetition().with(id(competitionId)) .withApplicationFinanceType(NO_FINANCES) .build(); when(competitionRepositoryMock.findById(competitionId)).thenReturn(Optional.of(c)); ServiceResult<Void> save = service.save(compSetupFinanceRes); assertTrue(save.isSuccess()); assertEquals(STANDARD, c.getApplicationFinanceType()); assertFalse(c.getIncludeProjectGrowthTable()); assertFalse(c.getIncludeYourOrganisationSection()); assertEquals(c.getIncludeJesForm(), includeJesForm); } |
### Question:
CompetitionSetupStakeholderServiceImpl extends BaseTransactionalService implements CompetitionSetupStakeholderService { @Override @Transactional public ServiceResult<Void> removeStakeholder(long competitionId, long stakeholderUserId) { stakeholderRepository.deleteStakeholder(competitionId, stakeholderUserId); return serviceSuccess(); } @Override @Transactional ServiceResult<Void> inviteStakeholder(UserResource invitedUser, long competitionId); @Override ServiceResult<List<UserResource>> findStakeholders(long competitionId); @Override ServiceResult<StakeholderInviteResource> getInviteByHash(String hash); @Override @Transactional ServiceResult<Void> addStakeholder(long competitionId, long stakeholderUserId); @Override @Transactional ServiceResult<Void> removeStakeholder(long competitionId, long stakeholderUserId); @Override @Transactional ServiceResult<List<UserResource>> findPendingStakeholderInvites(long competitionId); }### Answer:
@Test public void removeStakeholder() throws Exception { long competitionId = 1L; long stakeholderUserId = 2L; ServiceResult<Void> result = service.removeStakeholder(competitionId, stakeholderUserId); assertTrue(result.isSuccess()); verify(stakeholderRepositoryMock).deleteStakeholder(competitionId, stakeholderUserId); } |
### Question:
EmailAddressResolver { public static EmailAddress fromNotificationTarget(NotificationTarget notificationTarget) { return new EmailAddress(notificationTarget.getEmailAddress(), notificationTarget.getName()); } private EmailAddressResolver(); static EmailAddress fromNotificationSource(NotificationSource notificationSource); static EmailAddress fromNotificationTarget(NotificationTarget notificationTarget); }### Answer:
@Test public void testFromNotificationTargetWithUserNotificationTarget() { User user = newUser().withFirstName("My").withLastName("User").withEmailAddress("[email protected]").build(); UserNotificationTarget notificationTarget = new UserNotificationTarget(user.getName(), user.getEmail()); EmailAddress resolvedEmailAddress = EmailAddressResolver.fromNotificationTarget(notificationTarget); assertEquals("My User", resolvedEmailAddress.getName()); assertEquals("[email protected]", resolvedEmailAddress.getEmailAddress()); } |
### Question:
AssessorCountOptionServiceImpl extends BaseTransactionalService implements AssessorCountOptionService { @Override public ServiceResult<List<AssessorCountOptionResource>> findAllByCompetitionType(Long competitionTypeId) { return serviceSuccess(simpleMap(assessorCountOptionRepository.findByCompetitionTypeId(competitionTypeId), assessorCountOptionMapper::mapToResource)); } @Override ServiceResult<List<AssessorCountOptionResource>> findAllByCompetitionType(Long competitionTypeId); }### Answer:
@Test public void testFindAllByCompetitionType() throws Exception { List<AssessorCountOption> options = AssessorCountOptionFixture.programmeAssessorOptionsList(); List<AssessorCountOptionResource> expectedResponse = AssessorCountOptionFixture.programmeAssessorOptionResourcesList(); when(assessorCountOptionRepositoryMock.findByCompetitionTypeId(anyLong())).thenReturn(options); when(assessorCountOptionMapperMock.mapToResource(same(options.get(0)))).thenReturn((expectedResponse.get(0))); when(assessorCountOptionMapperMock.mapToResource(same(options.get(1)))).thenReturn((expectedResponse.get(1))); when(assessorCountOptionMapperMock.mapToResource(same(options.get(2)))).thenReturn((expectedResponse.get(2))); List<AssessorCountOptionResource> actualResponse = assessorCountOptionService.findAllByCompetitionType(1L).getSuccess(); assertEquals(expectedResponse, actualResponse); verify(assessorCountOptionRepositoryMock, only()).findByCompetitionTypeId(1L); } |
### Question:
ProfileController { @GetMapping("/id/{userId}/get-profile-skills") public RestResult<ProfileSkillsResource> getProfileSkills(@PathVariable("userId") long userId) { return profileService.getProfileSkills(userId).toGetResponse(); } @GetMapping("/id/{userId}/get-profile-skills") RestResult<ProfileSkillsResource> getProfileSkills(@PathVariable("userId") long userId); @PutMapping("/id/{userId}/update-profile-skills") RestResult<Void> updateProfileSkills(@PathVariable("userId") long id,
@Valid @RequestBody ProfileSkillsEditResource profileSkills); @GetMapping("/id/{userId}/get-profile-agreement") RestResult<ProfileAgreementResource> getProfileAgreement(@PathVariable("userId") long userId); @PutMapping("/id/{userId}/update-profile-agreement") RestResult<Void> updateProfileAgreement(@PathVariable("userId") long userId); @GetMapping("/id/{userId}/get-user-profile") RestResult<UserProfileResource> getUserProfile(@PathVariable("userId") Long userId); @PutMapping("/id/{userId}/update-user-profile") RestResult<Void> updateUserProfile(@PathVariable("userId") Long userId,
@RequestBody UserProfileResource profileDetails); @GetMapping("/id/{userId}/profile-status") RestResult<UserProfileStatusResource> getUserProfileStatus(@PathVariable("userId") Long userId); }### Answer:
@Test public void getProfileSkills() throws Exception { Long userId = 1L; ProfileSkillsResource profileSkillsResource = newProfileSkillsResource().build(); when(profileServiceMock.getProfileSkills(userId)).thenReturn(serviceSuccess(profileSkillsResource)); mockMvc.perform(get("/profile/id/{id}/get-profile-skills", userId)) .andExpect(status().isOk()) .andExpect(content().string(toJson(profileSkillsResource))); verify(profileServiceMock, only()).getProfileSkills(userId); } |
### Question:
ProfileController { @GetMapping("/id/{userId}/get-profile-agreement") public RestResult<ProfileAgreementResource> getProfileAgreement(@PathVariable("userId") long userId) { return profileService.getProfileAgreement(userId).toGetResponse(); } @GetMapping("/id/{userId}/get-profile-skills") RestResult<ProfileSkillsResource> getProfileSkills(@PathVariable("userId") long userId); @PutMapping("/id/{userId}/update-profile-skills") RestResult<Void> updateProfileSkills(@PathVariable("userId") long id,
@Valid @RequestBody ProfileSkillsEditResource profileSkills); @GetMapping("/id/{userId}/get-profile-agreement") RestResult<ProfileAgreementResource> getProfileAgreement(@PathVariable("userId") long userId); @PutMapping("/id/{userId}/update-profile-agreement") RestResult<Void> updateProfileAgreement(@PathVariable("userId") long userId); @GetMapping("/id/{userId}/get-user-profile") RestResult<UserProfileResource> getUserProfile(@PathVariable("userId") Long userId); @PutMapping("/id/{userId}/update-user-profile") RestResult<Void> updateUserProfile(@PathVariable("userId") Long userId,
@RequestBody UserProfileResource profileDetails); @GetMapping("/id/{userId}/profile-status") RestResult<UserProfileStatusResource> getUserProfileStatus(@PathVariable("userId") Long userId); }### Answer:
@Test public void getProfileAgreement() throws Exception { Long userId = 1L; ProfileAgreementResource profileAgreementResource = newProfileAgreementResource().build(); when(profileServiceMock.getProfileAgreement(userId)).thenReturn(serviceSuccess(profileAgreementResource)); mockMvc.perform(get("/profile/id/{id}/get-profile-agreement", userId)) .andExpect(status().isOk()) .andExpect(content().string(toJson(profileAgreementResource))); verify(profileServiceMock, only()).getProfileAgreement(userId); } |
### Question:
ProfileController { @PutMapping("/id/{userId}/update-profile-agreement") public RestResult<Void> updateProfileAgreement(@PathVariable("userId") long userId) { return profileService.updateProfileAgreement(userId).toPutResponse(); } @GetMapping("/id/{userId}/get-profile-skills") RestResult<ProfileSkillsResource> getProfileSkills(@PathVariable("userId") long userId); @PutMapping("/id/{userId}/update-profile-skills") RestResult<Void> updateProfileSkills(@PathVariable("userId") long id,
@Valid @RequestBody ProfileSkillsEditResource profileSkills); @GetMapping("/id/{userId}/get-profile-agreement") RestResult<ProfileAgreementResource> getProfileAgreement(@PathVariable("userId") long userId); @PutMapping("/id/{userId}/update-profile-agreement") RestResult<Void> updateProfileAgreement(@PathVariable("userId") long userId); @GetMapping("/id/{userId}/get-user-profile") RestResult<UserProfileResource> getUserProfile(@PathVariable("userId") Long userId); @PutMapping("/id/{userId}/update-user-profile") RestResult<Void> updateUserProfile(@PathVariable("userId") Long userId,
@RequestBody UserProfileResource profileDetails); @GetMapping("/id/{userId}/profile-status") RestResult<UserProfileStatusResource> getUserProfileStatus(@PathVariable("userId") Long userId); }### Answer:
@Test public void updateProfileAgreement() throws Exception { Long userId = 1L; when(profileServiceMock.updateProfileAgreement(userId)).thenReturn(serviceSuccess()); mockMvc.perform(put("/profile/id/{id}/update-profile-agreement", userId)) .andExpect(status().isOk()); verify(profileServiceMock, only()).updateProfileAgreement(userId); } |
### Question:
ProfileController { @GetMapping("/id/{userId}/get-user-profile") public RestResult<UserProfileResource> getUserProfile(@PathVariable("userId") Long userId) { return profileService.getUserProfile(userId).toGetResponse(); } @GetMapping("/id/{userId}/get-profile-skills") RestResult<ProfileSkillsResource> getProfileSkills(@PathVariable("userId") long userId); @PutMapping("/id/{userId}/update-profile-skills") RestResult<Void> updateProfileSkills(@PathVariable("userId") long id,
@Valid @RequestBody ProfileSkillsEditResource profileSkills); @GetMapping("/id/{userId}/get-profile-agreement") RestResult<ProfileAgreementResource> getProfileAgreement(@PathVariable("userId") long userId); @PutMapping("/id/{userId}/update-profile-agreement") RestResult<Void> updateProfileAgreement(@PathVariable("userId") long userId); @GetMapping("/id/{userId}/get-user-profile") RestResult<UserProfileResource> getUserProfile(@PathVariable("userId") Long userId); @PutMapping("/id/{userId}/update-user-profile") RestResult<Void> updateUserProfile(@PathVariable("userId") Long userId,
@RequestBody UserProfileResource profileDetails); @GetMapping("/id/{userId}/profile-status") RestResult<UserProfileStatusResource> getUserProfileStatus(@PathVariable("userId") Long userId); }### Answer:
@Test public void getProfileAddress() throws Exception { Long userId = 1L; UserProfileResource profileDetails = newUserProfileResource().build(); when(profileServiceMock.getUserProfile(userId)).thenReturn(serviceSuccess(profileDetails)); mockMvc.perform(get("/profile/id/{userId}/get-user-profile", userId) .contentType(APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string(toJson(profileDetails))); verify(profileServiceMock, only()).getUserProfile(userId); } |
### Question:
ProfileController { @PutMapping("/id/{userId}/update-user-profile") public RestResult<Void> updateUserProfile(@PathVariable("userId") Long userId, @RequestBody UserProfileResource profileDetails) { return profileService.updateUserProfile(userId, profileDetails).toPutResponse(); } @GetMapping("/id/{userId}/get-profile-skills") RestResult<ProfileSkillsResource> getProfileSkills(@PathVariable("userId") long userId); @PutMapping("/id/{userId}/update-profile-skills") RestResult<Void> updateProfileSkills(@PathVariable("userId") long id,
@Valid @RequestBody ProfileSkillsEditResource profileSkills); @GetMapping("/id/{userId}/get-profile-agreement") RestResult<ProfileAgreementResource> getProfileAgreement(@PathVariable("userId") long userId); @PutMapping("/id/{userId}/update-profile-agreement") RestResult<Void> updateProfileAgreement(@PathVariable("userId") long userId); @GetMapping("/id/{userId}/get-user-profile") RestResult<UserProfileResource> getUserProfile(@PathVariable("userId") Long userId); @PutMapping("/id/{userId}/update-user-profile") RestResult<Void> updateUserProfile(@PathVariable("userId") Long userId,
@RequestBody UserProfileResource profileDetails); @GetMapping("/id/{userId}/profile-status") RestResult<UserProfileStatusResource> getUserProfileStatus(@PathVariable("userId") Long userId); }### Answer:
@Test public void updateProfileAddress() throws Exception { UserProfileResource profileDetails = newUserProfileResource().build(); Long userId = 1L; when(profileServiceMock.updateUserProfile(userId, profileDetails)).thenReturn(serviceSuccess(newUserResource().build())); mockMvc.perform(put("/profile/id/{userId}/update-user-profile", userId) .contentType(APPLICATION_JSON) .content(objectMapper.writeValueAsString(profileDetails))) .andExpect(status().isOk()); verify(profileServiceMock, only()).updateUserProfile(userId, profileDetails); } |
### Question:
ProfileController { @GetMapping("/id/{userId}/profile-status") public RestResult<UserProfileStatusResource> getUserProfileStatus(@PathVariable("userId") Long userId) { return profileService.getUserProfileStatus(userId).toGetResponse(); } @GetMapping("/id/{userId}/get-profile-skills") RestResult<ProfileSkillsResource> getProfileSkills(@PathVariable("userId") long userId); @PutMapping("/id/{userId}/update-profile-skills") RestResult<Void> updateProfileSkills(@PathVariable("userId") long id,
@Valid @RequestBody ProfileSkillsEditResource profileSkills); @GetMapping("/id/{userId}/get-profile-agreement") RestResult<ProfileAgreementResource> getProfileAgreement(@PathVariable("userId") long userId); @PutMapping("/id/{userId}/update-profile-agreement") RestResult<Void> updateProfileAgreement(@PathVariable("userId") long userId); @GetMapping("/id/{userId}/get-user-profile") RestResult<UserProfileResource> getUserProfile(@PathVariable("userId") Long userId); @PutMapping("/id/{userId}/update-user-profile") RestResult<Void> updateUserProfile(@PathVariable("userId") Long userId,
@RequestBody UserProfileResource profileDetails); @GetMapping("/id/{userId}/profile-status") RestResult<UserProfileStatusResource> getUserProfileStatus(@PathVariable("userId") Long userId); }### Answer:
@Test public void getUserProfileStatus() throws Exception { UserProfileStatusResource profileStatus = newUserProfileStatusResource().build(); Long userId = 1L; when(profileServiceMock.getUserProfileStatus(userId)).thenReturn(serviceSuccess(profileStatus)); mockMvc.perform(get("/profile/id/{userId}/profile-status", userId) .contentType(APPLICATION_JSON) .content(objectMapper.writeValueAsString(profileStatus))) .andExpect(status().isOk()); verify(profileServiceMock, only()).getUserProfileStatus(userId); } |
### Question:
Profile extends AuditableEntity { public void addInnovationAreas(Set<InnovationArea> innovationAreas) { innovationAreas.forEach(this::addInnovationArea); } Profile(); void signAgreement(Agreement agreement, ZonedDateTime signedDate); Long getId(); void setId(Long id); Address getAddress(); void setAddress(Address address); String getSkillsAreas(); void setSkillsAreas(String skillsAreas); Set<InnovationArea> getInnovationAreas(); void addInnovationArea(InnovationArea innovationArea); void addInnovationAreas(Set<InnovationArea> innovationAreas); BusinessType getBusinessType(); void setBusinessType(BusinessType businessType); Agreement getAgreement(); void setAgreement(Agreement agreement); ZonedDateTime getAgreementSignedDate(); void setAgreementSignedDate(ZonedDateTime agreementSignedDate); boolean isCompliant(User user); static boolean isAffiliationsComplete(User user); static LocalDate startOfCurrentFinancialYear(ZonedDateTime now); ZonedDateTime getDoiNotifiedOn(); void setDoiNotifiedOn(ZonedDateTime doiNotifiedOn); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void testAddInnovationAreas() { InnovationArea expectedInnovationArea1 = newInnovationArea().withName("Innovation Area A").build(); InnovationArea expectedInnovationArea2 = newInnovationArea().withName("Innovation Area B").build(); Profile profile = newProfile().build(); profile.addInnovationAreas(newHashSet(expectedInnovationArea1, expectedInnovationArea2)); Set<InnovationArea> innovationAreas = profile.getInnovationAreas(); assertEquals(2, innovationAreas.size()); assertTrue(innovationAreas.contains(expectedInnovationArea1)); assertTrue(innovationAreas.contains(expectedInnovationArea2)); } |
### Question:
RestGrantEndpoint implements GrantEndpoint { @Override public ServiceResult<Void> send(Grant grant) { List<Grant> grantAsList = singletonList(grant); Either<ResponseEntity<Void>, ResponseEntity<JsonNode>> response = adaptor.restPostWithEntity(silRestServiceUrl + path, grantAsList, JsonNode.class, Void.class, HttpStatus.OK, HttpStatus.ACCEPTED); return response.mapLeftOrRight( failure -> { LOG.debug("Sent grant FAILURE : " + toJson(grant)); return serviceFailure(new Error(GRANT_PROCESS_SEND_FAILED, failure.getStatusCode())); }, success -> { LOG.debug("Sent grant SUCCESS : " + toJson(grant)); return serviceSuccess(); } ); } @Override ServiceResult<Void> send(Grant grant); }### Answer:
@Test public void send() { Grant grant = new Grant(); String expectedUrl = "http: ResponseEntity<String> returnedEntity = new ResponseEntity<>( new ObjectNode(jsonNodeFactory).put("Success", "Accepted").toString(), ACCEPTED); when(mockRestTemplate.postForEntity(expectedUrl, adaptor.jsonEntity(singletonList(grant)), String.class)) .thenReturn(returnedEntity); ServiceResult<Void> sendProjectResult = service.send(grant); assertTrue(sendProjectResult.isSuccess()); }
@Test public void send_failure() { Grant grant = new Grant(); String expectedUrl = "http: ResponseEntity<String> returnedEntity = new ResponseEntity<>(INTERNAL_SERVER_ERROR); when(mockRestTemplate.postForEntity(expectedUrl, adaptor.jsonEntity(singletonList(grant)), String.class)) .thenReturn(returnedEntity); ServiceResult<Void> sendProjectResult = service.send(grant); assertTrue(sendProjectResult.isFailure()); Error error = sendProjectResult.getFailure().getErrors().get(0); assertThat(error.getStatusCode(), equalTo(INTERNAL_SERVER_ERROR)); assertThat(error.getErrorKey(), equalTo(GRANT_PROCESS_SEND_FAILED.getErrorKey())); } |
### Question:
RestSilCrmEndpoint implements SilCrmEndpoint { @Override public ServiceResult<Void> updateContact(SilContact silContact) { return handlingErrors(() -> { final Either<ResponseEntity<SilCrmError>, ResponseEntity<Void>> response = adaptor.restPostWithEntity(silRestServiceUrl + silCrmContacts, silContact, Void.class, SilCrmError.class, HttpStatus.ACCEPTED); return response.mapLeftOrRight(failure -> { LOG.error("Error updating SIL contact " + silContact); return serviceFailure(new Error(CONTACT_NOT_UPDATED)); }, success -> serviceSuccess()); } ); } @Override ServiceResult<Void> updateContact(SilContact silContact); }### Answer:
@Test public void testUpdateContact() { SilContact silContact = new SilContact(); String expectedUrl = "http: ResponseEntity<String> returnedEntity = new ResponseEntity<>(ACCEPTED); when(mockRestTemplate.postForEntity(expectedUrl, adaptor.jsonEntity(silContact), String.class)).thenReturn(returnedEntity); ServiceResult<Void> sendMailResult = service.updateContact(silContact); assertTrue(sendMailResult.isSuccess()); } |
### Question:
SpendProfileCostFilter { public List<FinanceCostTotalResource> filterBySpendProfile(List<FinanceCostTotalResource> financeCostTotalResources) { return simpleFilter( financeCostTotalResources, financeResource -> financeResource.getFinanceRowType().isIncludedInSpendProfile() ); } List<FinanceCostTotalResource> filterBySpendProfile(List<FinanceCostTotalResource> financeCostTotalResources); }### Answer:
@Test public void filterBySpendProfile() { List<FinanceCostTotalResource> financeCostTotalResources = newFinanceCostTotalResource() .withFinanceRowType(FinanceRowType.values()) .build(FinanceRowType.values().length); List<FinanceCostTotalResource> financeCostTotalResourceResult = spendProfileCostFilter .filterBySpendProfile(financeCostTotalResources); List<FinanceCostTotalResource> expectedCostTotalResources = newFinanceCostTotalResource() .withFinanceRowType( FinanceRowType.LABOUR, FinanceRowType.OVERHEADS, FinanceRowType.MATERIALS, FinanceRowType.CAPITAL_USAGE, FinanceRowType.SUBCONTRACTING_COSTS, FinanceRowType.TRAVEL, FinanceRowType.OTHER_COSTS, FinanceRowType.PROCUREMENT_OVERHEADS, FinanceRowType.VAT, FinanceRowType.ASSOCIATE_SALARY_COSTS, FinanceRowType.ASSOCIATE_DEVELOPMENT_COSTS, FinanceRowType.CONSUMABLES, FinanceRowType.ASSOCIATE_SUPPORT, FinanceRowType.KNOWLEDGE_BASE, FinanceRowType.ESTATE_COSTS, FinanceRowType.KTP_TRAVEL ) .build(16); assertThat(financeCostTotalResourceResult) .usingRecursiveFieldByFieldElementComparator() .containsExactlyInAnyOrder(expectedCostTotalResources.toArray(new FinanceCostTotalResource[expectedCostTotalResources.size()])); } |
### Question:
AllFinanceTotalsSenderImpl implements AllFinanceTotalsSender { @Override @Transactional(readOnly = true) public ServiceResult<Void> sendAllFinanceTotals() { LOG.debug("Initiating sendAllFinanceTotals."); try (Stream<Application> applications = submittedApplicationsStream()) { applications.forEach(application -> applicationFinanceTotalsSender.sendFinanceTotalsForApplication(application.getId())); } LOG.debug("Completed sendAllFinanceTotals"); return ServiceResult.serviceSuccess(); } @Override @Transactional(readOnly = true) ServiceResult<Void> sendAllFinanceTotals(); }### Answer:
@Test public void sendAllFinanceTotals() { Stream<Application> applicationsStream = newApplication() .withCompetition(newCompetition().withId(1L).build()) .build(2) .stream(); when(applicationRepository.findByApplicationProcessActivityStateIn(submittedAndFinishedStates)) .thenReturn(applicationsStream); ServiceResult<Void> serviceResult = allFinanceTotalsSender.sendAllFinanceTotals(); assertTrue(serviceResult.isSuccess()); verify(applicationRepository, only()).findByApplicationProcessActivityStateIn(any()); verify(applicationFinanceTotalsSender, times(2)).sendFinanceTotalsForApplication(any()); verifyNoMoreInteractions(applicationRepository, applicationFinanceTotalsSender); } |
### Question:
AsyncRestCostTotalEndpoint { public ServiceResult<Void> sendCostTotals(Long applicationId, List<FinanceCostTotalResource> financeCostTotalResources) { sendCostTotalsCompletable(applicationId, financeCostTotalResources); return ServiceResult.serviceSuccess(); } @Autowired AsyncRestCostTotalEndpoint(
@Qualifier("finance_data_service_adaptor") AbstractRestTemplateAdaptor restTemplateAdaptor,
HashBasedMacTokenHandler hashBasedMacTokenHandler,
@Value("${ifs.finance-totals.authSecretKey}") String financeTotalsKey
); ServiceResult<Void> sendCostTotals(Long applicationId,
List<FinanceCostTotalResource> financeCostTotalResources); }### Answer:
@Test public void sendCostTotals() throws Exception { String url = "/cost-totals"; List<FinanceCostTotalResource> costTotalResources = newFinanceCostTotalResource() .build(2); HttpHeaders authHeader = new HttpHeaders(); authHeader.add("X-AUTH-TOKEN", hashBasedMacTokenHandler.calculateHash("supersecretkey", toJson(costTotalResources))); when(restTemplateAdaptorMock.restPostWithEntityAsync(url, costTotalResources, authHeader, Void.class)) .thenReturn(new CompletableFuture<>()); costTotalEndpoint.sendCostTotals(1L, costTotalResources); verify(restTemplateAdaptorMock).restPostWithEntityAsync(url, costTotalResources, authHeader, Void.class); } |
### Question:
ApplicationFinanceRowController { @PostMapping public RestResult<FinanceRowItem> create(@RequestBody final FinanceRowItem financeRowItem) { return applicationFinanceRowService.create(financeRowItem.getTargetId(), financeRowItem).toPostCreateResponse(); } @GetMapping("/{id}") RestResult<FinanceRowItem> get(@PathVariable final long id); @PostMapping RestResult<FinanceRowItem> create(@RequestBody final FinanceRowItem financeRowItem); @PutMapping("/{id}") RestResult<ValidationMessages> update(@PathVariable final long id, @RequestBody final FinanceRowItem financeRowItem); @DeleteMapping("/{id}") RestResult<Void> delete(@PathVariable final long id); }### Answer:
@Test public void create() throws Exception { FinanceRowItem financeRowItem = new GrantClaimPercentage(1L); when(financeRowCostsServiceMock.create(1L, financeRowItem)).thenReturn(serviceSuccess(new GrantClaimPercentage(1L))); mockMvc.perform(post("/application-finance-row") .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(financeRowItem))) .andExpect(status().isCreated()); verify(financeRowCostsServiceMock, times(1)).create(1L, financeRowItem); } |
### Question:
ApplicationFinanceRowController { @DeleteMapping("/{id}") public RestResult<Void> delete(@PathVariable final long id) { return applicationFinanceRowService.delete(id).toDeleteResponse(); } @GetMapping("/{id}") RestResult<FinanceRowItem> get(@PathVariable final long id); @PostMapping RestResult<FinanceRowItem> create(@RequestBody final FinanceRowItem financeRowItem); @PutMapping("/{id}") RestResult<ValidationMessages> update(@PathVariable final long id, @RequestBody final FinanceRowItem financeRowItem); @DeleteMapping("/{id}") RestResult<Void> delete(@PathVariable final long id); }### Answer:
@Test public void deleteCostAPICallShouldRenderResponse() throws Exception { when(financeRowCostsServiceMock.delete(123L)).thenReturn(serviceSuccess()); mockMvc.perform(delete("/application-finance-row/123")) .andExpect(status().isNoContent()); verify(financeRowCostsServiceMock, times(1)).delete(123L); } |
### Question:
ProjectFinanceRowController { @DeleteMapping("/{id}") public RestResult<Void> delete(@PathVariable final long id) { return projectFinanceRowService.delete(id).toDeleteResponse(); } @PostMapping RestResult<FinanceRowItem> addWithResponse(@RequestBody final FinanceRowItem financeRowItem); @GetMapping("/{id}") RestResult<FinanceRowItem> get(@PathVariable final long id); @PutMapping("/{id}") RestResult<ValidationMessages> update(@PathVariable final long id, @RequestBody final FinanceRowItem financeRowItem); @DeleteMapping("/{id}") RestResult<Void> delete(@PathVariable final long id); }### Answer:
@Test public void deleteCostAPICallShouldRenderResponse() throws Exception { when(projectFinanceRowServiceMock.delete(123L)).thenReturn(serviceSuccess()); mockMvc.perform(delete("/project-finance-row/123")) .andExpect(status().isNoContent()); verify(projectFinanceRowServiceMock, times(1)).delete(123L); } |
### Question:
GrantClaimMaximumController { @GetMapping("/{id}") public RestResult<GrantClaimMaximumResource> getGrantClaimMaximumById(@PathVariable("id") final long id) { return grantClaimMaximumService.getGrantClaimMaximumById(id).toGetResponse(); } GrantClaimMaximumController(GrantClaimMaximumService grantClaimMaximumService); @GetMapping("/{id}") RestResult<GrantClaimMaximumResource> getGrantClaimMaximumById(@PathVariable("id") final long id); @PostMapping("/revert-to-default/{competitionId}") RestResult<Set<Long>> revertToDefault(@PathVariable("competitionId") final long competitionId); @PostMapping("/") RestResult<GrantClaimMaximumResource> update(@RequestBody final GrantClaimMaximumResource gcm); @GetMapping("/maximum-funding-level-overridden/{competitionId}") RestResult<Boolean> isMaximumFundingLevelOverridden(@PathVariable("competitionId") final long competitionId); }### Answer:
@Test public void getGrantClaimMaximumById() throws Exception { GrantClaimMaximumResource gcm = newGrantClaimMaximumResource().build(); when(grantClaimMaximumService.getGrantClaimMaximumById(gcm.getId())).thenReturn(serviceSuccess(gcm)); mockMvc.perform(get("/grant-claim-maximum/{id}", gcm.getId())) .andExpect(status().isOk()) .andExpect(content().json(toJson(gcm))); verify(grantClaimMaximumService, only()).getGrantClaimMaximumById(gcm.getId()); }
@Test public void getGrantClaimMaximumByIdNotFound() throws Exception { when(grantClaimMaximumService.getGrantClaimMaximumById(1L)).thenReturn(serviceFailure(notFoundError(GrantClaimMaximum.class, 1L))); mockMvc.perform(get("/grant-claim-maximum/{id}", 1L)) .andExpect(status().isNotFound()); verify(grantClaimMaximumService, only()).getGrantClaimMaximumById(1L); } |
### Question:
GrantClaimMaximumController { @GetMapping("/maximum-funding-level-overridden/{competitionId}") public RestResult<Boolean> isMaximumFundingLevelOverridden(@PathVariable("competitionId") final long competitionId) { return grantClaimMaximumService.isMaximumFundingLevelOverridden(competitionId).toGetResponse(); } GrantClaimMaximumController(GrantClaimMaximumService grantClaimMaximumService); @GetMapping("/{id}") RestResult<GrantClaimMaximumResource> getGrantClaimMaximumById(@PathVariable("id") final long id); @PostMapping("/revert-to-default/{competitionId}") RestResult<Set<Long>> revertToDefault(@PathVariable("competitionId") final long competitionId); @PostMapping("/") RestResult<GrantClaimMaximumResource> update(@RequestBody final GrantClaimMaximumResource gcm); @GetMapping("/maximum-funding-level-overridden/{competitionId}") RestResult<Boolean> isMaximumFundingLevelOverridden(@PathVariable("competitionId") final long competitionId); }### Answer:
@Test public void isMaximumFundingLevelOverridden() throws Exception { long competitionId = 1L; boolean expectedResult = true; when(grantClaimMaximumService.isMaximumFundingLevelOverridden(competitionId)).thenReturn(serviceSuccess (expectedResult)); mockMvc.perform(get("/grant-claim-maximum/maximum-funding-level-overridden/{competitionId}", competitionId) .contentType(MediaType.APPLICATION_JSON)) .andExpect(content().string(String.valueOf(expectedResult))) .andExpect(status().isOk()); verify(grantClaimMaximumService).isMaximumFundingLevelOverridden(competitionId); } |
### Question:
CostTotalMaintenanceController { @PutMapping("/send-all") public RestResult<Void> sendAll() { return allFinanceTotalsSender.sendAllFinanceTotals().toPutResponse(); } @PutMapping("/send-all") RestResult<Void> sendAll(); }### Answer:
@Test public void sendAll() throws Exception { when(allFinanceTotalsSenderMock.sendAllFinanceTotals()).thenReturn(ServiceResult.serviceSuccess()); mockMvc.perform(put("/cost/send-all")) .andExpect(status().isOk()); verify(allFinanceTotalsSenderMock, only()).sendAllFinanceTotals(); } |
### Question:
ProjectFinanceHandlerImpl implements ProjectFinanceHandler { @Override @Transactional public BigDecimal getResearchParticipationPercentageFromProject(long projectId){ List<ProjectFinanceResource> applicationFinanceResources = this.getFinanceChecksTotals(projectId); BigDecimal totalCosts = applicationFinanceResources.stream() .map(ProjectFinanceResource::getTotal) .reduce(BigDecimal.ZERO, BigDecimal::add); BigDecimal researchCosts = applicationFinanceResources.stream() .filter(f -> OrganisationTypeEnum.isResearchParticipationOrganisation(organisationRepository.findById(f.getOrganisation()).get().getOrganisationType().getId()) ) .map(ProjectFinanceResource::getTotal) .reduce(BigDecimal.ZERO, BigDecimal::add); BigDecimal researchParticipation = BigDecimal.ZERO; if(totalCosts.compareTo(BigDecimal.ZERO)!=0) { researchParticipation = researchCosts.divide(totalCosts, 6, BigDecimal.ROUND_HALF_UP); } researchParticipation = researchParticipation.multiply(BigDecimal.valueOf(100)); return researchParticipation.setScale(2, BigDecimal.ROUND_HALF_UP); } @Override @Transactional BigDecimal getResearchParticipationPercentageFromProject(long projectId); @Override @Transactional ServiceResult<ProjectFinanceResource> getProjectOrganisationFinances(ProjectFinanceResourceId projectFinanceResourceId); @Override @Transactional List<ProjectFinanceResource> getFinanceChecksTotals(long projectId); }### Answer:
@Test public void getResearchParticipationPercentageFromProject() { BigDecimal result = handler.getResearchParticipationPercentageFromProject(projectId); assertNotNull(result); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.