method2testcases
stringlengths
118
6.63k
### Question: KeycloakPreAuthActionsFilter extends GenericFilterBean implements ApplicationContextAware { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpFacade facade = new SimpleHttpFacade((HttpServletRequest)request, (HttpServletResponse)response); KeycloakDeployment deployment = deploymentContext.resolveDeployment(facade); if (deployment == null) { return; } if (deployment.isConfigured()) { nodesRegistrationManagement.tryRegister(deploymentContext.resolveDeployment(facade)); } PreAuthActionsHandler handler = preAuthActionsHandlerFactory.createPreAuthActionsHandler(facade); if (handler.handleRequest()) { log.debug("Pre-auth filter handled request: {}", ((HttpServletRequest) request).getRequestURI()); } else { chain.doFilter(request, response); } } KeycloakPreAuthActionsFilter(); KeycloakPreAuthActionsFilter(UserSessionManagement userSessionManagement); @Override void destroy(); @Override void doFilter(ServletRequest request, ServletResponse response, FilterChain chain); void setUserSessionManagement(UserSessionManagement userSessionManagement); @Override void setApplicationContext(ApplicationContext applicationContext); }### Answer: @Test public void shouldIgnoreChainWhenPreAuthActionHandlerHandled() throws Exception { when(preAuthActionsHandler.handleRequest()).thenReturn(true); filter.doFilter(request, response, chain); verifyZeroInteractions(chain); verify(nodesRegistrationManagement).tryRegister(deployment); } @Test public void shouldContinueChainWhenPreAuthActionHandlerDidNotHandle() throws Exception { when(preAuthActionsHandler.handleRequest()).thenReturn(false); filter.doFilter(request, response, chain); verify(chain).doFilter(request, response);; verify(nodesRegistrationManagement).tryRegister(deployment); }
### Question: QueryParamPresenceRequestMatcher implements RequestMatcher { @Override public boolean matches(HttpServletRequest httpServletRequest) { return param != null && httpServletRequest.getParameter(param) != null; } QueryParamPresenceRequestMatcher(String param); @Override boolean matches(HttpServletRequest httpServletRequest); }### Answer: @Test public void testDoesNotMatchWithoutQueryParameter() throws Exception { prepareRequest(HttpMethod.GET, ROOT_CONTEXT_PATH, "some/random/uri", Collections.EMPTY_MAP); assertFalse(matcher.matches(request)); } @Test public void testMatchesWithValidParameter() throws Exception { prepareRequest(HttpMethod.GET, ROOT_CONTEXT_PATH, "some/random/uri", Collections.singletonMap(VALID_PARAMETER, (Object) "123")); assertTrue(matcher.matches(request)); } @Test public void testDoesNotMatchWithInvalidParameter() throws Exception { prepareRequest(HttpMethod.GET, ROOT_CONTEXT_PATH, "some/random/uri", Collections.singletonMap("some_parameter", (Object) "123")); assertFalse(matcher.matches(request)); }
### Question: KeycloakCsrfRequestMatcher implements RequestMatcher { public boolean matches(HttpServletRequest request) { String uri = request.getRequestURI().replaceFirst(request.getContextPath(), ""); return !allowedEndpoints.matcher(uri).matches() && !allowedMethods.matcher(request.getMethod()).matches(); } boolean matches(HttpServletRequest request); }### Answer: @Test public void testMatchesMethodGet() throws Exception { request.setMethod(HttpMethod.GET.name()); assertFalse(matcher.matches(request)); } @Test public void testMatchesMethodPost() throws Exception { prepareRequest(HttpMethod.POST, ROOT_CONTEXT_PATH, "some/random/uri"); assertTrue(matcher.matches(request)); prepareRequest(HttpMethod.POST, SUB_CONTEXT_PATH, "some/random/uri"); assertTrue(matcher.matches(request)); } @Test public void testMatchesKeycloakLogout() throws Exception { prepareRequest(HttpMethod.POST, ROOT_CONTEXT_PATH, AdapterConstants.K_LOGOUT); assertFalse(matcher.matches(request)); prepareRequest(HttpMethod.POST, SUB_CONTEXT_PATH, AdapterConstants.K_LOGOUT); assertFalse(matcher.matches(request)); } @Test public void testMatchesKeycloakPushNotBefore() throws Exception { prepareRequest(HttpMethod.POST, ROOT_CONTEXT_PATH, AdapterConstants.K_PUSH_NOT_BEFORE); assertFalse(matcher.matches(request)); prepareRequest(HttpMethod.POST, SUB_CONTEXT_PATH, AdapterConstants.K_PUSH_NOT_BEFORE); assertFalse(matcher.matches(request)); } @Test public void testMatchesKeycloakQueryBearerToken() throws Exception { prepareRequest(HttpMethod.POST, ROOT_CONTEXT_PATH, AdapterConstants.K_QUERY_BEARER_TOKEN); assertFalse(matcher.matches(request)); prepareRequest(HttpMethod.POST, SUB_CONTEXT_PATH, AdapterConstants.K_QUERY_BEARER_TOKEN); assertFalse(matcher.matches(request)); } @Test public void testMatchesKeycloakTestAvailable() throws Exception { prepareRequest(HttpMethod.POST, ROOT_CONTEXT_PATH, AdapterConstants.K_TEST_AVAILABLE); assertFalse(matcher.matches(request)); prepareRequest(HttpMethod.POST, SUB_CONTEXT_PATH, AdapterConstants.K_TEST_AVAILABLE); assertFalse(matcher.matches(request)); }
### Question: KeycloakAuthenticationProcessingFilter extends AbstractAuthenticationProcessingFilter implements ApplicationContextAware { @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { log.debug("Attempting Keycloak authentication"); HttpFacade facade = new SimpleHttpFacade(request, response); KeycloakDeployment deployment = adapterDeploymentContext.resolveDeployment(facade); deployment.setDelegateBearerErrorResponseSending(true); AdapterTokenStore tokenStore = adapterTokenStoreFactory.createAdapterTokenStore(deployment, request, response); RequestAuthenticator authenticator = requestAuthenticatorFactory.createRequestAuthenticator(facade, request, deployment, tokenStore, -1); AuthOutcome result = authenticator.authenticate(); log.debug("Auth outcome: {}", result); if (AuthOutcome.FAILED.equals(result)) { AuthChallenge challenge = authenticator.getChallenge(); if (challenge != null) { challenge.challenge(facade); } throw new KeycloakAuthenticationException("Invalid authorization header, see WWW-Authenticate header for details"); } if (AuthOutcome.NOT_ATTEMPTED.equals(result)) { AuthChallenge challenge = authenticator.getChallenge(); if (challenge != null) { challenge.challenge(facade); } if (deployment.isBearerOnly()) { throw new KeycloakAuthenticationException("Authorization header not found, see WWW-Authenticate header"); } else { return null; } } else if (AuthOutcome.AUTHENTICATED.equals(result)) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Assert.notNull(authentication, "Authentication SecurityContextHolder was null"); return authenticationManager.authenticate(authentication); } else { AuthChallenge challenge = authenticator.getChallenge(); if (challenge != null) { challenge.challenge(facade); } return null; } } KeycloakAuthenticationProcessingFilter(AuthenticationManager authenticationManager); KeycloakAuthenticationProcessingFilter(AuthenticationManager authenticationManager, RequestMatcher requiresAuthenticationRequestMatcher); @Override void afterPropertiesSet(); @Override Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response); @Override void setApplicationContext(ApplicationContext applicationContext); void setAdapterTokenStoreFactory(AdapterTokenStoreFactory adapterTokenStoreFactory); @Override final void setAllowSessionCreation(boolean allowSessionCreation); @Override final void setContinueChainBeforeSuccessfulAuthentication(boolean continueChainBeforeSuccessfulAuthentication); void setRequestAuthenticatorFactory(RequestAuthenticatorFactory requestAuthenticatorFactory); static final String AUTHORIZATION_HEADER; static final RequestMatcher DEFAULT_REQUEST_MATCHER; }### Answer: @Test public void testAttemptAuthenticationExpectRedirect() throws Exception { when(keycloakDeployment.getAuthUrl()).thenReturn(KeycloakUriBuilder.fromUri("http: when(keycloakDeployment.getResourceName()).thenReturn("resource-name"); when(keycloakDeployment.getStateCookieName()).thenReturn("kc-cookie"); when(keycloakDeployment.getSslRequired()).thenReturn(SslRequired.NONE); when(keycloakDeployment.isBearerOnly()).thenReturn(Boolean.FALSE); filter.attemptAuthentication(request, response); verify(response).setStatus(302); verify(response).setHeader(eq("Location"), startsWith("http: } @Test(expected = KeycloakAuthenticationException.class) public void testAttemptAuthenticationWithInvalidToken() throws Exception { request.addHeader("Authorization", "Bearer xxx"); filter.attemptAuthentication(request, response); } @Test(expected = KeycloakAuthenticationException.class) public void testAttemptAuthenticationWithInvalidTokenBearerOnly() throws Exception { when(keycloakDeployment.isBearerOnly()).thenReturn(Boolean.TRUE); request.addHeader("Authorization", "Bearer xxx"); filter.attemptAuthentication(request, response); }
### Question: KeycloakAuthenticationProcessingFilter extends AbstractAuthenticationProcessingFilter implements ApplicationContextAware { @Override protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException { if (authResult instanceof KeycloakAuthenticationToken && ((KeycloakAuthenticationToken) authResult).isInteractive()) { super.successfulAuthentication(request, response, chain, authResult); return; } if (log.isDebugEnabled()) { log.debug("Authentication success using bearer token/basic authentication. Updating SecurityContextHolder to contain: {}", authResult); } SecurityContext context = SecurityContextHolder.createEmptyContext(); context.setAuthentication(authResult); SecurityContextHolder.setContext(context); try { if (this.eventPublisher != null) { eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(authResult, this.getClass())); } chain.doFilter(request, response); } finally { SecurityContextHolder.clearContext(); } } KeycloakAuthenticationProcessingFilter(AuthenticationManager authenticationManager); KeycloakAuthenticationProcessingFilter(AuthenticationManager authenticationManager, RequestMatcher requiresAuthenticationRequestMatcher); @Override void afterPropertiesSet(); @Override Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response); @Override void setApplicationContext(ApplicationContext applicationContext); void setAdapterTokenStoreFactory(AdapterTokenStoreFactory adapterTokenStoreFactory); @Override final void setAllowSessionCreation(boolean allowSessionCreation); @Override final void setContinueChainBeforeSuccessfulAuthentication(boolean continueChainBeforeSuccessfulAuthentication); void setRequestAuthenticatorFactory(RequestAuthenticatorFactory requestAuthenticatorFactory); static final String AUTHORIZATION_HEADER; static final RequestMatcher DEFAULT_REQUEST_MATCHER; }### Answer: @Test public void testSuccessfulAuthenticationInteractive() throws Exception { request.setRequestURI("http: Authentication authentication = new KeycloakAuthenticationToken(keycloakAccount, true, authorities); filter.successfulAuthentication(request, response, chain, authentication); verify(successHandler).onAuthenticationSuccess(eq(request), eq(response), eq(authentication)); verify(chain, never()).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class)); } @Test public void testSuccessfulAuthenticationBearer() throws Exception { Authentication authentication = new KeycloakAuthenticationToken(keycloakAccount, false, authorities); this.setBearerAuthHeader(request); filter.successfulAuthentication(request, response, chain, authentication); verify(chain).doFilter(eq(request), eq(response)); verify(successHandler, never()).onAuthenticationSuccess(any(HttpServletRequest.class), any(HttpServletResponse.class), any(Authentication.class)); } @Test public void testSuccessfulAuthenticationBasicAuth() throws Exception { Authentication authentication = new KeycloakAuthenticationToken(keycloakAccount, false, authorities); this.setBasicAuthHeader(request); filter.successfulAuthentication(request, response, chain, authentication); verify(chain).doFilter(eq(request), eq(response)); verify(successHandler, never()).onAuthenticationSuccess(any(HttpServletRequest.class), any(HttpServletResponse.class), any(Authentication.class)); }
### Question: KeycloakAuthenticationProcessingFilter extends AbstractAuthenticationProcessingFilter implements ApplicationContextAware { @Override protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException { super.unsuccessfulAuthentication(request, response, failed); } KeycloakAuthenticationProcessingFilter(AuthenticationManager authenticationManager); KeycloakAuthenticationProcessingFilter(AuthenticationManager authenticationManager, RequestMatcher requiresAuthenticationRequestMatcher); @Override void afterPropertiesSet(); @Override Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response); @Override void setApplicationContext(ApplicationContext applicationContext); void setAdapterTokenStoreFactory(AdapterTokenStoreFactory adapterTokenStoreFactory); @Override final void setAllowSessionCreation(boolean allowSessionCreation); @Override final void setContinueChainBeforeSuccessfulAuthentication(boolean continueChainBeforeSuccessfulAuthentication); void setRequestAuthenticatorFactory(RequestAuthenticatorFactory requestAuthenticatorFactory); static final String AUTHORIZATION_HEADER; static final RequestMatcher DEFAULT_REQUEST_MATCHER; }### Answer: @Test public void testUnsuccessfulAuthenticationInteractive() throws Exception { AuthenticationException exception = new BadCredentialsException("OOPS"); filter.unsuccessfulAuthentication(request, response, exception); verify(failureHandler).onAuthenticationFailure(eq(request), eq(response), eq(exception)); } @Test public void testUnsuccessfulAuthenticatioBearer() throws Exception { AuthenticationException exception = new BadCredentialsException("OOPS"); this.setBearerAuthHeader(request); filter.unsuccessfulAuthentication(request, response, exception); verify(failureHandler).onAuthenticationFailure(any(HttpServletRequest.class), any(HttpServletResponse.class), any(AuthenticationException.class)); } @Test public void testUnsuccessfulAuthenticatioBasicAuth() throws Exception { AuthenticationException exception = new BadCredentialsException("OOPS"); this.setBasicAuthHeader(request); filter.unsuccessfulAuthentication(request, response, exception); verify(failureHandler).onAuthenticationFailure(any(HttpServletRequest.class), any(HttpServletResponse.class), any(AuthenticationException.class)); } @Test public void testDefaultFailureHanlder() throws Exception { AuthenticationException exception = new BadCredentialsException("OOPS"); filter.setAuthenticationFailureHandler(keycloakFailureHandler); filter.unsuccessfulAuthentication(request, response, exception); verify(response).sendError(eq(HttpServletResponse.SC_UNAUTHORIZED), any(String.class)); }
### Question: KeycloakAuthenticationProcessingFilter extends AbstractAuthenticationProcessingFilter implements ApplicationContextAware { @Override public final void setAllowSessionCreation(boolean allowSessionCreation) { throw new UnsupportedOperationException("This filter does not support explicitly setting a session creation policy"); } KeycloakAuthenticationProcessingFilter(AuthenticationManager authenticationManager); KeycloakAuthenticationProcessingFilter(AuthenticationManager authenticationManager, RequestMatcher requiresAuthenticationRequestMatcher); @Override void afterPropertiesSet(); @Override Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response); @Override void setApplicationContext(ApplicationContext applicationContext); void setAdapterTokenStoreFactory(AdapterTokenStoreFactory adapterTokenStoreFactory); @Override final void setAllowSessionCreation(boolean allowSessionCreation); @Override final void setContinueChainBeforeSuccessfulAuthentication(boolean continueChainBeforeSuccessfulAuthentication); void setRequestAuthenticatorFactory(RequestAuthenticatorFactory requestAuthenticatorFactory); static final String AUTHORIZATION_HEADER; static final RequestMatcher DEFAULT_REQUEST_MATCHER; }### Answer: @Test(expected = UnsupportedOperationException.class) public void testSetAllowSessionCreation() throws Exception { filter.setAllowSessionCreation(true); }
### Question: KeycloakAuthenticationProcessingFilter extends AbstractAuthenticationProcessingFilter implements ApplicationContextAware { @Override public final void setContinueChainBeforeSuccessfulAuthentication(boolean continueChainBeforeSuccessfulAuthentication) { throw new UnsupportedOperationException("This filter does not support explicitly setting a continue chain before success policy"); } KeycloakAuthenticationProcessingFilter(AuthenticationManager authenticationManager); KeycloakAuthenticationProcessingFilter(AuthenticationManager authenticationManager, RequestMatcher requiresAuthenticationRequestMatcher); @Override void afterPropertiesSet(); @Override Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response); @Override void setApplicationContext(ApplicationContext applicationContext); void setAdapterTokenStoreFactory(AdapterTokenStoreFactory adapterTokenStoreFactory); @Override final void setAllowSessionCreation(boolean allowSessionCreation); @Override final void setContinueChainBeforeSuccessfulAuthentication(boolean continueChainBeforeSuccessfulAuthentication); void setRequestAuthenticatorFactory(RequestAuthenticatorFactory requestAuthenticatorFactory); static final String AUTHORIZATION_HEADER; static final RequestMatcher DEFAULT_REQUEST_MATCHER; }### Answer: @Test(expected = UnsupportedOperationException.class) public void testSetContinueChainBeforeSuccessfulAuthentication() throws Exception { filter.setContinueChainBeforeSuccessfulAuthentication(true); }
### Question: SpringSecurityAdapterTokenStoreFactory implements AdapterTokenStoreFactory { @Override public AdapterTokenStore createAdapterTokenStore(KeycloakDeployment deployment, HttpServletRequest request, HttpServletResponse response) { Assert.notNull(deployment, "KeycloakDeployment is required"); if (deployment.getTokenStore() == TokenStore.COOKIE) { return new SpringSecurityCookieTokenStore(deployment, request, response); } return new SpringSecurityTokenStore(deployment, request); } @Override AdapterTokenStore createAdapterTokenStore(KeycloakDeployment deployment, HttpServletRequest request, HttpServletResponse response); }### Answer: @Test public void testCreateAdapterTokenStore() throws Exception { when(deployment.getTokenStore()).thenReturn(TokenStore.SESSION); AdapterSessionStore store = factory.createAdapterTokenStore(deployment, request, response); assertTrue(store instanceof SpringSecurityTokenStore); } @Test public void testCreateAdapterTokenStoreUsingCookies() throws Exception { when(deployment.getTokenStore()).thenReturn(TokenStore.COOKIE); AdapterSessionStore store = factory.createAdapterTokenStore(deployment, request, response); assertTrue(store instanceof SpringSecurityCookieTokenStore); } @Test(expected = IllegalArgumentException.class) public void testCreateAdapterTokenStoreNullDeployment() throws Exception { factory.createAdapterTokenStore(null, request, response); } @Test(expected = IllegalArgumentException.class) public void testCreateAdapterTokenStoreNullRequest() throws Exception { factory.createAdapterTokenStore(deployment, null, response); } @Test public void testCreateAdapterTokenStoreNullResponse() throws Exception { when(deployment.getTokenStore()).thenReturn(TokenStore.SESSION); factory.createAdapterTokenStore(deployment, request, null); } @Test(expected = IllegalArgumentException.class) public void testCreateAdapterTokenStoreNullResponseUsingCookies() throws Exception { when(deployment.getTokenStore()).thenReturn(TokenStore.COOKIE); factory.createAdapterTokenStore(deployment, request, null); }
### Question: SpringSecurityTokenStore implements AdapterTokenStore { @Override public boolean isCached(RequestAuthenticator authenticator) { logger.debug("Checking if {} is cached", authenticator); SecurityContext context = SecurityContextHolder.getContext(); KeycloakAuthenticationToken token; KeycloakSecurityContext keycloakSecurityContext; if (context == null || context.getAuthentication() == null) { return false; } if (!KeycloakAuthenticationToken.class.isAssignableFrom(context.getAuthentication().getClass())) { logger.warn("Expected a KeycloakAuthenticationToken, but found {}", context.getAuthentication()); return false; } logger.debug("Remote logged in already. Establishing state from security context."); token = (KeycloakAuthenticationToken) context.getAuthentication(); keycloakSecurityContext = token.getAccount().getKeycloakSecurityContext(); if (!deployment.getRealm().equals(keycloakSecurityContext.getRealm())) { logger.debug("Account from security context is from a different realm than for the request."); logout(); return false; } if (keycloakSecurityContext.getToken().isExpired()) { logger.warn("Security token expired ... not returning from cache"); return false; } request.setAttribute(KeycloakSecurityContext.class.getName(), keycloakSecurityContext); return true; } SpringSecurityTokenStore(KeycloakDeployment deployment, HttpServletRequest request); @Override void checkCurrentToken(); @Override boolean isCached(RequestAuthenticator authenticator); @Override void saveAccountInfo(OidcKeycloakAccount account); @Override void logout(); @Override void refreshCallback(RefreshableKeycloakSecurityContext securityContext); @Override void saveRequest(); @Override boolean restoreRequest(); }### Answer: @Test public void testIsCached() throws Exception { Authentication authentication = new PreAuthenticatedAuthenticationToken("foo", "bar", Collections.singleton(new KeycloakRole("ROLE_FOO"))); SecurityContextHolder.getContext().setAuthentication(authentication); assertFalse(store.isCached(requestAuthenticator)); }
### Question: SpringSecurityTokenStore implements AdapterTokenStore { @Override public void saveAccountInfo(OidcKeycloakAccount account) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null) { throw new IllegalStateException(String.format("Went to save Keycloak account %s, but already have %s", account, authentication)); } logger.debug("Saving account info {}", account); SecurityContext context = SecurityContextHolder.createEmptyContext(); context.setAuthentication(new KeycloakAuthenticationToken(account, true)); SecurityContextHolder.setContext(context); } SpringSecurityTokenStore(KeycloakDeployment deployment, HttpServletRequest request); @Override void checkCurrentToken(); @Override boolean isCached(RequestAuthenticator authenticator); @Override void saveAccountInfo(OidcKeycloakAccount account); @Override void logout(); @Override void refreshCallback(RefreshableKeycloakSecurityContext securityContext); @Override void saveRequest(); @Override boolean restoreRequest(); }### Answer: @Test public void testSaveAccountInfo() throws Exception { OidcKeycloakAccount account = new SimpleKeycloakAccount(principal, Collections.singleton("FOO"), keycloakSecurityContext); Authentication authentication; store.saveAccountInfo(account); authentication = SecurityContextHolder.getContext().getAuthentication(); assertNotNull(authentication); assertTrue(authentication instanceof KeycloakAuthenticationToken); } @Test(expected = IllegalStateException.class) public void testSaveAccountInfoInvalidAuthenticationType() throws Exception { OidcKeycloakAccount account = new SimpleKeycloakAccount(principal, Collections.singleton("FOO"), keycloakSecurityContext); Authentication authentication = new PreAuthenticatedAuthenticationToken("foo", "bar", Collections.singleton(new KeycloakRole("ROLE_FOO"))); SecurityContextHolder.getContext().setAuthentication(authentication); store.saveAccountInfo(account); }
### Question: ProxyMappings { public boolean isEmpty() { return this.entries.isEmpty(); } ProxyMappings(List<ProxyMapping> entries); static ProxyMappings valueOf(List<String> proxyMappings); static ProxyMappings valueOf(String... proxyMappings); boolean isEmpty(); ProxyMapping getProxyFor(String hostname); static void clearCache(); }### Answer: @Test public void proxyMappingFromEmptyListShouldBeEmpty() { assertThat(new ProxyMappings(new ArrayList<>()).isEmpty(), is(true)); }
### Question: SpringSecurityTokenStore implements AdapterTokenStore { @Override public void logout() { logger.debug("Handling logout request"); HttpSession session = request.getSession(false); if (session != null) { session.setAttribute(KeycloakSecurityContext.class.getName(), null); session.invalidate(); } SecurityContextHolder.clearContext(); } SpringSecurityTokenStore(KeycloakDeployment deployment, HttpServletRequest request); @Override void checkCurrentToken(); @Override boolean isCached(RequestAuthenticator authenticator); @Override void saveAccountInfo(OidcKeycloakAccount account); @Override void logout(); @Override void refreshCallback(RefreshableKeycloakSecurityContext securityContext); @Override void saveRequest(); @Override boolean restoreRequest(); }### Answer: @Test public void testLogout() throws Exception { MockHttpSession session = (MockHttpSession) request.getSession(true); assertFalse(session.isInvalid()); store.logout(); assertTrue(session.isInvalid()); }
### Question: AdapterDeploymentContextFactoryBean implements FactoryBean<AdapterDeploymentContext>, InitializingBean { @Override public void afterPropertiesSet() throws Exception { if (keycloakConfigResolver != null) { adapterDeploymentContext = new AdapterDeploymentContext(keycloakConfigResolver); } else { log.info("Loading Keycloak deployment from configuration file: {}", keycloakConfigFileResource); KeycloakDeployment deployment = loadKeycloakDeployment(); adapterDeploymentContext = new AdapterDeploymentContext(deployment); } } AdapterDeploymentContextFactoryBean(Resource keycloakConfigFileResource); AdapterDeploymentContextFactoryBean(KeycloakConfigResolver keycloakConfigResolver); @Override Class<?> getObjectType(); @Override boolean isSingleton(); @Override void afterPropertiesSet(); @Override AdapterDeploymentContext getObject(); }### Answer: @Test public void should_throw_exception_when_configuration_file_was_not_found() throws Exception { adapterDeploymentContextFactoryBean = new AdapterDeploymentContextFactoryBean(getEmptyResource()); expectedException.expect(FileNotFoundException.class); expectedException.expectMessage("Unable to locate Keycloak configuration file: no-file.json"); adapterDeploymentContextFactoryBean.afterPropertiesSet(); }
### Question: WrappedHttpServletResponse implements Response { @Override public void resetCookie(String name, String path) { Cookie cookie = new Cookie(name, ""); cookie.setMaxAge(0); if (path != null) { cookie.setPath(path); } response.addCookie(cookie); } WrappedHttpServletResponse(HttpServletResponse response); @Override void resetCookie(String name, String path); @Override void setCookie(String name, String value, String path, String domain, int maxAge, boolean secure, boolean httpOnly); @Override void setStatus(int status); @Override void addHeader(String name, String value); @Override void setHeader(String name, String value); @Override OutputStream getOutputStream(); @Override void sendError(int code); @Override void sendError(int code, String message); @Override void end(); }### Answer: @Test public void testResetCookie() throws Exception { response.resetCookie(COOKIE_NAME, COOKIE_PATH); verify(mockResponse).addCookie(any(Cookie.class)); assertEquals(COOKIE_NAME, mockResponse.getCookie(COOKIE_NAME).getName()); assertEquals(COOKIE_PATH, mockResponse.getCookie(COOKIE_NAME).getPath()); assertEquals(0, mockResponse.getCookie(COOKIE_NAME).getMaxAge()); assertEquals("", mockResponse.getCookie(COOKIE_NAME).getValue()); }
### Question: WrappedHttpServletResponse implements Response { @Override public void setCookie(String name, String value, String path, String domain, int maxAge, boolean secure, boolean httpOnly) { Cookie cookie = new Cookie(name, value); if (path != null) { cookie.setPath(path); } if (domain != null) { cookie.setDomain(domain); } cookie.setMaxAge(maxAge); cookie.setSecure(secure); this.setHttpOnly(cookie, httpOnly); response.addCookie(cookie); } WrappedHttpServletResponse(HttpServletResponse response); @Override void resetCookie(String name, String path); @Override void setCookie(String name, String value, String path, String domain, int maxAge, boolean secure, boolean httpOnly); @Override void setStatus(int status); @Override void addHeader(String name, String value); @Override void setHeader(String name, String value); @Override OutputStream getOutputStream(); @Override void sendError(int code); @Override void sendError(int code, String message); @Override void end(); }### Answer: @Test public void testSetCookie() throws Exception { int maxAge = 300; response.setCookie(COOKIE_NAME, COOKIE_VALUE, COOKIE_PATH, COOKIE_DOMAIN, maxAge, false, true); verify(mockResponse).addCookie(any(Cookie.class)); assertEquals(COOKIE_NAME, mockResponse.getCookie(COOKIE_NAME).getName()); assertEquals(COOKIE_PATH, mockResponse.getCookie(COOKIE_NAME).getPath()); assertEquals(COOKIE_DOMAIN, mockResponse.getCookie(COOKIE_NAME).getDomain()); assertEquals(maxAge, mockResponse.getCookie(COOKIE_NAME).getMaxAge()); assertEquals(COOKIE_VALUE, mockResponse.getCookie(COOKIE_NAME).getValue()); assertEquals(true, mockResponse.getCookie(COOKIE_NAME).isHttpOnly()); }
### Question: WrappedHttpServletResponse implements Response { @Override public void setStatus(int status) { response.setStatus(status); } WrappedHttpServletResponse(HttpServletResponse response); @Override void resetCookie(String name, String path); @Override void setCookie(String name, String value, String path, String domain, int maxAge, boolean secure, boolean httpOnly); @Override void setStatus(int status); @Override void addHeader(String name, String value); @Override void setHeader(String name, String value); @Override OutputStream getOutputStream(); @Override void sendError(int code); @Override void sendError(int code, String message); @Override void end(); }### Answer: @Test public void testSetStatus() throws Exception { int status = HttpStatus.OK.value(); response.setStatus(status); verify(mockResponse).setStatus(eq(status)); assertEquals(status, mockResponse.getStatus()); }
### Question: WrappedHttpServletResponse implements Response { @Override public void addHeader(String name, String value) { response.addHeader(name, value); } WrappedHttpServletResponse(HttpServletResponse response); @Override void resetCookie(String name, String path); @Override void setCookie(String name, String value, String path, String domain, int maxAge, boolean secure, boolean httpOnly); @Override void setStatus(int status); @Override void addHeader(String name, String value); @Override void setHeader(String name, String value); @Override OutputStream getOutputStream(); @Override void sendError(int code); @Override void sendError(int code, String message); @Override void end(); }### Answer: @Test public void testAddHeader() throws Exception { String headerValue = "foo"; response.addHeader(HEADER, headerValue); verify(mockResponse).addHeader(eq(HEADER), eq(headerValue)); assertTrue(mockResponse.containsHeader(HEADER)); }
### Question: WrappedHttpServletResponse implements Response { @Override public void setHeader(String name, String value) { response.setHeader(name, value); } WrappedHttpServletResponse(HttpServletResponse response); @Override void resetCookie(String name, String path); @Override void setCookie(String name, String value, String path, String domain, int maxAge, boolean secure, boolean httpOnly); @Override void setStatus(int status); @Override void addHeader(String name, String value); @Override void setHeader(String name, String value); @Override OutputStream getOutputStream(); @Override void sendError(int code); @Override void sendError(int code, String message); @Override void end(); }### Answer: @Test public void testSetHeader() throws Exception { String headerValue = "foo"; response.setHeader(HEADER, headerValue); verify(mockResponse).setHeader(eq(HEADER), eq(headerValue)); assertTrue(mockResponse.containsHeader(HEADER)); }
### Question: WrappedHttpServletResponse implements Response { @Override public OutputStream getOutputStream() { try { return response.getOutputStream(); } catch (IOException e) { throw new RuntimeException("Unable to return response output stream", e); } } WrappedHttpServletResponse(HttpServletResponse response); @Override void resetCookie(String name, String path); @Override void setCookie(String name, String value, String path, String domain, int maxAge, boolean secure, boolean httpOnly); @Override void setStatus(int status); @Override void addHeader(String name, String value); @Override void setHeader(String name, String value); @Override OutputStream getOutputStream(); @Override void sendError(int code); @Override void sendError(int code, String message); @Override void end(); }### Answer: @Test public void testGetOutputStream() throws Exception { assertNotNull(response.getOutputStream()); verify(mockResponse).getOutputStream(); }
### Question: WrappedHttpServletResponse implements Response { @Override public void sendError(int code) { try { response.sendError(code); } catch (IOException e) { throw new RuntimeException("Unable to set HTTP status", e); } } WrappedHttpServletResponse(HttpServletResponse response); @Override void resetCookie(String name, String path); @Override void setCookie(String name, String value, String path, String domain, int maxAge, boolean secure, boolean httpOnly); @Override void setStatus(int status); @Override void addHeader(String name, String value); @Override void setHeader(String name, String value); @Override OutputStream getOutputStream(); @Override void sendError(int code); @Override void sendError(int code, String message); @Override void end(); }### Answer: @Test public void testSendError() throws Exception { int status = HttpStatus.UNAUTHORIZED.value(); String reason = HttpStatus.UNAUTHORIZED.getReasonPhrase(); response.sendError(status, reason); verify(mockResponse).sendError(eq(status), eq(reason)); assertEquals(status, mockResponse.getStatus()); assertEquals(reason, mockResponse.getErrorMessage()); }
### Question: WrappedHttpServletResponse implements Response { @Override public void end() { } WrappedHttpServletResponse(HttpServletResponse response); @Override void resetCookie(String name, String path); @Override void setCookie(String name, String value, String path, String domain, int maxAge, boolean secure, boolean httpOnly); @Override void setStatus(int status); @Override void addHeader(String name, String value); @Override void setHeader(String name, String value); @Override OutputStream getOutputStream(); @Override void sendError(int code); @Override void sendError(int code, String message); @Override void end(); }### Answer: @Test @Ignore public void testEnd() throws Exception { }
### Question: Invoice extends UdoDomainObject2<T> implements WithApplicationTenancyAny, WithApplicationTenancyPathPersisted { @Property(notPersisted = true) public BigDecimal getTotalNetAmount() { return sum(InvoiceItem::getNetAmount); } Invoice(final String keyProperties); @Property(hidden = Where.ALL_TABLES) @PropertyLayout( named = "Application Level", describedAs = "Determines those users for whom this object is available to view and/or modify." ) ApplicationTenancy getApplicationTenancy(); String title(); @Property(hidden = Where.OBJECT_FORMS) String getNumber(); @Action( semantics = SemanticsOf.IDEMPOTENT, restrictTo = RestrictTo.PROTOTYPING ) Invoice updateAttribute( final InvoiceAttributeName name, @Parameter(maxLength = NotesType.Meta.MAX_LEN) @ParameterLayout(multiLine = Invoice.DescriptionType.Meta.MULTI_LINE) final String value, InvoiceAttributeAction action ); @Action(semantics = SemanticsOf.IDEMPOTENT) Invoice changeDueDate(final LocalDate dueDate); LocalDate default0ChangeDueDate(final LocalDate dueDate); String disableChangeDueDate(); @Action(semantics = SemanticsOf.IDEMPOTENT) Invoice changePaymentMethod(final PaymentMethod paymentMethod); PaymentMethod default0ChangePaymentMethod(); String disableChangePaymentMethod(); String validateChangePaymentMethod(final PaymentMethod paymentMethod); @Programmatic BigInteger nextItemSequence(); @Property(notPersisted = true) BigDecimal getTotalNetAmount(); @Property(notPersisted = true, hidden = Where.ALL_TABLES) BigDecimal getTotalVatAmount(); @Property(notPersisted = true) BigDecimal getTotalGrossAmount(); @Programmatic boolean isImmutableDueToState(); @Programmatic InvoiceItem findFirstItemWithCharge(final Charge charge); Invoice verify(); boolean hideVerify(); }### Answer: @Test public void netAmount() throws Exception { InvoiceForTesting invoiceForTesting = new InvoiceForTesting(); InvoiceItemForTesting item1 = new InvoiceItemForTesting(invoiceForTesting); item1.setNetAmount(new BigDecimal("123.45")); InvoiceItemForTesting item2 = new InvoiceItemForTesting(invoiceForTesting); item2.setNetAmount(new BigDecimal("543.21")); invoiceForTesting.getItems().add(item1); invoiceForTesting.getItems().add(item2); assertThat(invoiceForTesting.getItems()).hasSize(2); BigDecimal netAmount = invoiceForTesting.getTotalNetAmount(); assertThat(netAmount).isEqualTo(new BigDecimal("666.66")); }
### Question: LocationLookupService { @Programmatic public Location lookup(final String description) { RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(TIMEOUT_SECONDS * 1000) .setConnectTimeout(TIMEOUT_SECONDS * 1000) .build(); CloseableHttpClient httpClient = HttpClientBuilder.create() .setDefaultRequestConfig(requestConfig) .useSystemProperties() .build(); try { String uri = BASEURL + MODE + "?address=" + URLEncoder.encode(description, "UTF-8") + "&sensor=false"; HttpGet httpGet = new HttpGet(uri); CloseableHttpResponse response = httpClient.execute(httpGet); try { HttpEntity entity = response.getEntity(); return extractLocation(EntityUtils.toString(entity, "UTF-8")); } finally { response.close(); } } catch (Exception ex) { return null; } } @Programmatic Location lookup(final String description); }### Answer: @Ignore @Test public void whenValid() { Location location = locationLookupService.lookup("10 Downing Street,London,UK"); assertThat(location, is(not(nullValue()))); assertEquals(51.503, location.getLatitude(), 0.01); assertEquals(-0.128, location.getLongitude(), 0.01); } @Ignore @Test public void whenInvalid() { Location location = locationLookupService.lookup("$%$%^Y%^fgnsdlfk glfg"); assertThat(location, is(nullValue())); }
### Question: PdfManipulator { @Programmatic public byte[] extractAndStamp( final byte[] docBytes, final ExtractSpec extractSpec, final Stamp stamp) throws IOException { List<byte[]> extractedPageDocBytes = Lists.newArrayList(); final PDDocument pdDoc = PDDocument.load(docBytes); try { final Splitter splitter = new Splitter(); final List<PDDocument> splitDocs = splitter.split(pdDoc); final int sizeOfDoc = splitDocs.size(); final Integer[] pageNums = extractSpec.pageNumbersFor(sizeOfDoc); for (Integer pageNum : pageNums) { final PDDocument docOfExtractedPage = splitDocs.get(pageNum); if(stamp != null) { final List<Line> leftLines = stamp.getLeftLines(); final List<Line> rightLines = stamp.getRightLines(); leftLines.add(new Line(String.format("Page: %d/%d", (pageNum+1), sizeOfDoc), TEXT_COLOR, null)); stamp.appendHyperlinkIfAnyTo(leftLines); extractedPageDocBytes.add(stamp(docOfExtractedPage, leftLines, rightLines)); } else { extractedPageDocBytes.add(asBytes(docOfExtractedPage)); } } for (PDDocument splitDoc : splitDocs) { splitDoc.close(); } } finally { pdDoc.close(); } final byte[] mergedBytes = pdfBoxService.merge(extractedPageDocBytes.toArray(new byte[][] {})); return mergedBytes; } @Programmatic byte[] stamp( final byte[] docBytes, final Stamp stamp); @Programmatic byte[] extract( final byte[] docBytes, final ExtractSpec extractSpec); @Programmatic byte[] extractAndStamp( final byte[] docBytes, final ExtractSpec extractSpec, final Stamp stamp); }### Answer: @Ignore @Test public void firstPageOf() throws Exception { URL resource = Resources.getResource(PdfManipulatorTest.class, "sample-invoice.pdf"); byte[] bytes = Resources.toByteArray(resource); Stamp stamp = new Stamp(Arrays.asList( "approved by: Joe Bloggs", "approved on: 3-May-2017 14:15", "doc barcode: 3013011234" ), Arrays.asList( "debtor IBAN: FR12345678900000123", "crdtor IBAN: FR99999912312399800", "gross amt : 12345.99" ), "http: final PdfManipulator pdfManipulator = new PdfManipulator(); pdfManipulator.pdfBoxService = new PdfBoxService(); byte[] firstPageBytes = pdfManipulator.extractAndStamp(bytes, new ExtractSpec(3,1), stamp); IOUtils.copy(new ByteArrayInputStream(firstPageBytes), new FileOutputStream("x.pdf")); }
### Question: FinancialAmountUtil { public static BigDecimal subtractHandlingNulls(final BigDecimal amount, final BigDecimal amountToSubtract) { if (amountToSubtract == null) return amount; return amount == null ? amountToSubtract.negate() : amount.subtract(amountToSubtract); } static BigDecimal subtractHandlingNulls(final BigDecimal amount, final BigDecimal amountToSubtract); static BigDecimal addHandlingNulls(final BigDecimal amount, final BigDecimal amountToAdd); static BigDecimal determineVatAmount( final BigDecimal netAmount, final BigDecimal grossAmount, final Tax tax, final LocalDate now); static BigDecimal determineNetAmount( final BigDecimal vatAmount, final BigDecimal grossAmount, final Tax tax, final LocalDate now); static BigDecimal determineGrossAmount( final BigDecimal netAmount, final BigDecimal vatAmount, final Tax tax, final LocalDate now); }### Answer: @Test public void subtractHandlingNulls() throws Exception { BigDecimal amount; BigDecimal amountToSubtract; BigDecimal result; amount = new BigDecimal("100"); amountToSubtract = new BigDecimal("10.11"); result = FinancialAmountUtil.subtractHandlingNulls(amount, amountToSubtract); Assertions.assertThat(result).isEqualTo(new BigDecimal("89.89")); amount = new BigDecimal("100"); amountToSubtract = null; result = FinancialAmountUtil.subtractHandlingNulls(amount, amountToSubtract); Assertions.assertThat(result).isEqualTo(new BigDecimal("100")); amount = null; amountToSubtract = new BigDecimal("10.11"); result = FinancialAmountUtil.subtractHandlingNulls(amount, amountToSubtract); Assertions.assertThat(result).isEqualTo(new BigDecimal("-10.11")); amount = null; amountToSubtract = null; result = FinancialAmountUtil.subtractHandlingNulls(amount, amountToSubtract); Assertions.assertThat(result).isNull(); }
### Question: FinancialAmountUtil { public static BigDecimal addHandlingNulls(final BigDecimal amount, final BigDecimal amountToAdd) { if (amountToAdd == null) return amount; return amount == null ? amountToAdd : amount.add(amountToAdd); } static BigDecimal subtractHandlingNulls(final BigDecimal amount, final BigDecimal amountToSubtract); static BigDecimal addHandlingNulls(final BigDecimal amount, final BigDecimal amountToAdd); static BigDecimal determineVatAmount( final BigDecimal netAmount, final BigDecimal grossAmount, final Tax tax, final LocalDate now); static BigDecimal determineNetAmount( final BigDecimal vatAmount, final BigDecimal grossAmount, final Tax tax, final LocalDate now); static BigDecimal determineGrossAmount( final BigDecimal netAmount, final BigDecimal vatAmount, final Tax tax, final LocalDate now); }### Answer: @Test public void addHandlingNulls() throws Exception { BigDecimal amount; BigDecimal amountToAdd; BigDecimal result; amount = new BigDecimal("100"); amountToAdd = new BigDecimal("10.11"); result = FinancialAmountUtil.addHandlingNulls(amount, amountToAdd); Assertions.assertThat(result).isEqualTo(new BigDecimal("110.11")); amount = new BigDecimal("100"); amountToAdd = null; result = FinancialAmountUtil.addHandlingNulls(amount, amountToAdd); Assertions.assertThat(result).isEqualTo(new BigDecimal("100")); amount = null; amountToAdd = new BigDecimal("10.11"); result = FinancialAmountUtil.addHandlingNulls(amount, amountToAdd); Assertions.assertThat(result).isEqualTo(new BigDecimal("10.11")); amount = null; amountToAdd = null; result = FinancialAmountUtil.addHandlingNulls(amount, amountToAdd); Assertions.assertThat(result).isNull(); }
### Question: DocumentNameUtil { public static String stripPdfSuffixFromDocumentName(final String documentName){ return documentName.replaceAll("(?i)\\.pdf", ""); } static String stripPdfSuffixFromDocumentName(final String documentName); }### Answer: @Test public void stripPdfSuffixFromDocumentName() { Assertions.assertThat(DocumentNameUtil.stripPdfSuffixFromDocumentName("S123456789.PDF")).isEqualTo("S123456789"); Assertions.assertThat(DocumentNameUtil.stripPdfSuffixFromDocumentName("S123456789.pdf")).isEqualTo("S123456789"); Assertions.assertThat(DocumentNameUtil.stripPdfSuffixFromDocumentName("S123456789.pDf")).isEqualTo("S123456789"); Assertions.assertThat(DocumentNameUtil.stripPdfSuffixFromDocumentName("123456789.pDf")).isEqualTo("123456789"); Assertions.assertThat(DocumentNameUtil.stripPdfSuffixFromDocumentName("123456789.xml")).isEqualTo("123456789.xml"); Assertions.assertThat(DocumentNameUtil.stripPdfSuffixFromDocumentName("123456789..pDf")).isEqualTo("123456789."); Assertions.assertThat(DocumentNameUtil.stripPdfSuffixFromDocumentName("123456789..pDfX")).isEqualTo("123456789.X"); Assertions.assertThat(DocumentNameUtil.stripPdfSuffixFromDocumentName("S123456789.pD")).isEqualTo("S123456789.pD"); Assertions.assertThat(DocumentNameUtil.stripPdfSuffixFromDocumentName("S123456789pDf")).isEqualTo("S123456789pDf"); }
### Question: Invoice extends UdoDomainObject2<T> implements WithApplicationTenancyAny, WithApplicationTenancyPathPersisted { @Programmatic public InvoiceItem findFirstItemWithCharge(final Charge charge) { for (InvoiceItem item : getItems()) { if (item.getCharge().equals(charge)) { return item; } } return null; } Invoice(final String keyProperties); @Property(hidden = Where.ALL_TABLES) @PropertyLayout( named = "Application Level", describedAs = "Determines those users for whom this object is available to view and/or modify." ) ApplicationTenancy getApplicationTenancy(); String title(); @Property(hidden = Where.OBJECT_FORMS) String getNumber(); @Action( semantics = SemanticsOf.IDEMPOTENT, restrictTo = RestrictTo.PROTOTYPING ) Invoice updateAttribute( final InvoiceAttributeName name, @Parameter(maxLength = NotesType.Meta.MAX_LEN) @ParameterLayout(multiLine = Invoice.DescriptionType.Meta.MULTI_LINE) final String value, InvoiceAttributeAction action ); @Action(semantics = SemanticsOf.IDEMPOTENT) Invoice changeDueDate(final LocalDate dueDate); LocalDate default0ChangeDueDate(final LocalDate dueDate); String disableChangeDueDate(); @Action(semantics = SemanticsOf.IDEMPOTENT) Invoice changePaymentMethod(final PaymentMethod paymentMethod); PaymentMethod default0ChangePaymentMethod(); String disableChangePaymentMethod(); String validateChangePaymentMethod(final PaymentMethod paymentMethod); @Programmatic BigInteger nextItemSequence(); @Property(notPersisted = true) BigDecimal getTotalNetAmount(); @Property(notPersisted = true, hidden = Where.ALL_TABLES) BigDecimal getTotalVatAmount(); @Property(notPersisted = true) BigDecimal getTotalGrossAmount(); @Programmatic boolean isImmutableDueToState(); @Programmatic InvoiceItem findFirstItemWithCharge(final Charge charge); Invoice verify(); boolean hideVerify(); }### Answer: @Test public void first_item_with_charge_works() throws Exception { InvoiceForTesting invoice = new InvoiceForTesting(); Charge charge1 = new Charge(); Charge charge2 = new Charge(); InvoiceItem itemWithCharge1 = new InvoiceItemForTesting(invoice); itemWithCharge1.setCharge(charge1); itemWithCharge1.setSequence(VT.bi(1)); InvoiceItem otherItemWithCharge1 = new InvoiceItemForTesting(invoice); otherItemWithCharge1.setCharge(charge1); otherItemWithCharge1.setSequence(VT.bi(2)); InvoiceItem itemWithCharge2 = new InvoiceItemForTesting(invoice); itemWithCharge2.setCharge(charge2); invoice.getItems().addAll(Arrays.asList(itemWithCharge1, otherItemWithCharge1, itemWithCharge2)); assertThat(invoice.getItems().size()).isEqualTo(3); assertThat(invoice.findFirstItemWithCharge(charge1)).isEqualTo(itemWithCharge1); assertThat(invoice.findFirstItemWithCharge(charge2)).isEqualTo(itemWithCharge2); }
### Question: PeriodUtil { public static boolean isValidPeriod(final String period){ if (period!=null && !period.equals("") && !yearFromPeriod(period).equals(new LocalDateInterval(null, null))){ return true; } return false; } static LocalDate startDateFromPeriod(final String period); static LocalDate endDateFromPeriod(final String period); static LocalDateInterval fromPeriod(final String period); static LocalDateInterval yearFromPeriod(final String period); static String periodFromInterval(@NotNull final LocalDateInterval interval); static boolean isValidPeriod(final String period); static String reasonInvalidPeriod(final String period); static Pattern financialYearPattern; static Pattern yearPattern; }### Answer: @Test public void isValidPeriod() throws Exception { String period; period = "f2017M01"; Assertions.assertThat(PeriodUtil.isValidPeriod(period)).isEqualTo(false); Assertions.assertThat(PeriodUtil.reasonInvalidPeriod(period)).isEqualTo("Not a valid period; use four digits of the year with optional prefix F for a financial year (for example: F2017)"); period = "F2017M01"; Assertions.assertThat(PeriodUtil.isValidPeriod(period)).isEqualTo(true); Assertions.assertThat(PeriodUtil.reasonInvalidPeriod(period)).isNull(); period = ""; Assertions.assertThat(PeriodUtil.isValidPeriod(period)).isEqualTo(false); period = null; Assertions.assertThat(PeriodUtil.isValidPeriod(period)).isEqualTo(false); }
### Question: IncomingInvoiceExport { public static String getCodaElement6FromSellerReference(final String sellerReference){ if (sellerReference.startsWith("FR")) { return "FRFO".concat(sellerReference.substring(2)); } if (sellerReference.startsWith("BE")){ return "BEFO".concat(sellerReference.substring(2)); } return null; } IncomingInvoiceExport( final IncomingInvoiceItem item, final String documentNumber, final String comments ); static String deriveCodaElement1FromBuyer(Party buyer); static String getCodaElement6FromSellerReference(final String sellerReference); static String deriveCodaElement3FromPropertyAndIncomingInvoiceType(final FixedAsset property, final IncomingInvoiceType incomingInvoiceType, final String atPath); }### Answer: @Test public void getCodaElement6FromSellerReference() { String frenchSupplierRef = "FR12345"; Assertions.assertThat(IncomingInvoiceExport.getCodaElement6FromSellerReference(frenchSupplierRef)).isEqualTo("FRFO12345"); String belgianSupplierRef = "BE123456"; Assertions.assertThat(IncomingInvoiceExport.getCodaElement6FromSellerReference(belgianSupplierRef)).isEqualTo("BEFO123456"); String unknownSupplierRef = "UN123456"; Assertions.assertThat(IncomingInvoiceExport.getCodaElement6FromSellerReference(unknownSupplierRef)).isNull(); }
### Question: IncomingInvoiceExport { public static String deriveCodaElement3FromPropertyAndIncomingInvoiceType(final FixedAsset property, final IncomingInvoiceType incomingInvoiceType, final String atPath){ if (incomingInvoiceType==IncomingInvoiceType.CORPORATE_EXPENSES){ if (atPath!=null && atPath.startsWith("/BEL")){ return "BEGGEN0"; } return "FRGGEN0"; } if (incomingInvoiceType==IncomingInvoiceType.LOCAL_EXPENSES){ return "FRGPAR0"; } if (property!=null){ return property.getExternalReference(); } return null; } IncomingInvoiceExport( final IncomingInvoiceItem item, final String documentNumber, final String comments ); static String deriveCodaElement1FromBuyer(Party buyer); static String getCodaElement6FromSellerReference(final String sellerReference); static String deriveCodaElement3FromPropertyAndIncomingInvoiceType(final FixedAsset property, final IncomingInvoiceType incomingInvoiceType, final String atPath); }### Answer: @Test public void deriveCodaElement3FromPropertyAndIncomingInvoiceType(){ Assertions.assertThat(IncomingInvoiceExport.deriveCodaElement3FromPropertyAndIncomingInvoiceType(null, null, null)).isNull(); IncomingInvoiceType typeForCorporate = IncomingInvoiceType.CORPORATE_EXPENSES; Property property = new Property(); Assertions.assertThat(IncomingInvoiceExport.deriveCodaElement3FromPropertyAndIncomingInvoiceType(null, typeForCorporate, null)).isEqualTo("FRGGEN0"); Assertions.assertThat(IncomingInvoiceExport.deriveCodaElement3FromPropertyAndIncomingInvoiceType(property, typeForCorporate, null)).isEqualTo("FRGGEN0"); String atPath = "/BEL/Etc"; Assertions.assertThat(IncomingInvoiceExport.deriveCodaElement3FromPropertyAndIncomingInvoiceType(null, typeForCorporate, atPath)).isEqualTo("BEGGEN0"); Assertions.assertThat(IncomingInvoiceExport.deriveCodaElement3FromPropertyAndIncomingInvoiceType(property, typeForCorporate, atPath)).isEqualTo("BEGGEN0"); IncomingInvoiceType typeForLocal = IncomingInvoiceType.LOCAL_EXPENSES; Assertions.assertThat(IncomingInvoiceExport.deriveCodaElement3FromPropertyAndIncomingInvoiceType(null, typeForLocal, null)).isEqualTo("FRGPAR0"); Assertions.assertThat(IncomingInvoiceExport.deriveCodaElement3FromPropertyAndIncomingInvoiceType(property, typeForLocal, null)).isEqualTo("FRGPAR0"); IncomingInvoiceType typeForCapex = IncomingInvoiceType.CAPEX; Assertions.assertThat(IncomingInvoiceExport.deriveCodaElement3FromPropertyAndIncomingInvoiceType(null, typeForCapex, null)).isNull(); Assertions.assertThat(IncomingInvoiceExport.deriveCodaElement3FromPropertyAndIncomingInvoiceType(property, typeForCapex, null)).isNull(); property.setExternalReference("SOME_EXT_REF"); Assertions.assertThat(IncomingInvoiceExport.deriveCodaElement3FromPropertyAndIncomingInvoiceType(property, typeForCapex, null)).isEqualTo("SOME_EXT_REF"); }
### Question: IncomingInvoiceExport { public static String deriveCodaElement1FromBuyer(Party buyer) { if (buyer==null) return null; if (buyer.getReference().equals("BE00")){ return "BE01EUR"; } return buyer.getReference().concat("EUR"); } IncomingInvoiceExport( final IncomingInvoiceItem item, final String documentNumber, final String comments ); static String deriveCodaElement1FromBuyer(Party buyer); static String getCodaElement6FromSellerReference(final String sellerReference); static String deriveCodaElement3FromPropertyAndIncomingInvoiceType(final FixedAsset property, final IncomingInvoiceType incomingInvoiceType, final String atPath); }### Answer: @Test public void deriveCodaElement1FromBuyer() throws Exception { Party buyer = new Organisation(); Assertions.assertThat(IncomingInvoiceExport.deriveCodaElement1FromBuyer(null)).isNull(); buyer.setReference("SOMETHING"); Assertions.assertThat(IncomingInvoiceExport.deriveCodaElement1FromBuyer(buyer)).isEqualTo("SOMETHINGEUR"); buyer.setReference("BE00"); Assertions.assertThat(IncomingInvoiceExport.deriveCodaElement1FromBuyer(buyer)).isEqualTo("BE01EUR"); }
### Question: ChargingLine implements Importable { String keyToChargeReference() { return "SE" + getKod() + "-" + getKod2(); } ChargingLine(); String title(); @PropertyLayout(hidden = Where.PARENTED_TABLES) Lease getLease(); LeaseItem getLeaseItem(); @Action(semantics = SemanticsOf.NON_IDEMPOTENT) ImportStatus apply(); boolean hideApply(); @Action(semantics = SemanticsOf.IDEMPOTENT) ChargingLine discard(); boolean hideDiscard(); @Action(semantics = SemanticsOf.IDEMPOTENT) ChargingLine noUpdate(); boolean hideNoUpdate(); @Programmatic List<Object> importChargingLine(final boolean nonDiscardedOnly); @Override @Programmatic List<Object> importData(final Object previousRow); }### Answer: @Test public void keyToChargeReference() throws Exception { ChargingLine line = new ChargingLine(); line.setKod("123"); line.setKod2("4"); Assertions.assertThat(line.keyToChargeReference()).isEqualTo("SE123-4"); }
### Question: OrderProjectImportAdapter implements FixtureAwareRowHandler<OrderProjectImportAdapter>, ExcelMetaDataEnabled { public String deriveOrderNumber() { if (getNumero() == null) return null; StringBuilder builder = new StringBuilder(); builder.append(getNumero().toString()); builder.append("/"); if (getCentro() != null) builder.append(getCentro()); builder.append("/"); if (getProgressivoCentro() != null && getCommessa() != null) { builder.append(getProgressivoCentro()); builder.append("/"); builder.append(getCommessa()); } else if (getCommessa() != null && getWorkType() != null) { builder.append(getCommessa()); builder.append("/"); builder.append(getWorkType()); } else { if (getProgressivoCentro() != null) { builder.append(getProgressivoCentro()); } builder.append("/"); if (getCommessa() != null) { builder.append(getCommessa()); } } return builder.toString(); } OrderProjectImportAdapter handle(final OrderProjectImportAdapter previousRow); String deriveOrderNumber(); void correctProgressivoCentroIfNecessary(); String deriveProjectReference(); @Override void handleRow(final OrderProjectImportAdapter previousRow); }### Answer: @Test public void deriveOrderNumber() { OrderProjectImportAdapter adapter = new OrderProjectImportAdapter(); adapter.setNumero(2234); adapter.setCentro("CAR"); adapter.setProgressivoCentro("694"); adapter.setCommessa("192"); assertThat(adapter.deriveOrderNumber()).isEqualTo("2234/CAR/694/192"); } @Test public void deriveOrderNumber_when_nulls_oldFormat() { OrderProjectImportAdapter adapter = new OrderProjectImportAdapter(); adapter.setNumero(null); adapter.setCentro("CAR"); adapter.setProgressivoCentro("694"); adapter.setCommessa("192"); adapter.setWorkType(null); assertThat(adapter.deriveOrderNumber()).isNull(); adapter.setNumero(2234); adapter.setCentro(null); adapter.setProgressivoCentro("694"); adapter.setCommessa("192"); adapter.setWorkType(null); assertThat(adapter.deriveOrderNumber()).isEqualTo("2234 adapter.setNumero(2234); adapter.setCentro("CAR"); adapter.setProgressivoCentro(null); adapter.setCommessa("192"); adapter.setWorkType(null); assertThat(adapter.deriveOrderNumber()).isEqualTo("2234/CAR adapter.setNumero(2234); adapter.setCentro("CAR"); adapter.setProgressivoCentro("694"); adapter.setCommessa(null); adapter.setWorkType(null); assertThat(adapter.deriveOrderNumber()).isEqualTo("2234/CAR/694/"); } @Test public void deriveOrderNumber_when_nulls_newFormat() throws Exception { OrderProjectImportAdapter adapter = new OrderProjectImportAdapter(); adapter.setNumero(null); adapter.setCentro("CAR"); adapter.setProgressivoCentro(null); adapter.setCommessa("192"); adapter.setWorkType("001"); assertThat(adapter.deriveOrderNumber()).isNull(); adapter.setNumero(2234); adapter.setCentro(null); adapter.setProgressivoCentro(null); adapter.setCommessa("192"); adapter.setWorkType("001"); assertThat(adapter.deriveOrderNumber()).isEqualTo("2234 }
### Question: OrderProjectImportAdapter implements FixtureAwareRowHandler<OrderProjectImportAdapter>, ExcelMetaDataEnabled { public void correctProgressivoCentroIfNecessary() { if (getProgressivoCentro() != null && getProgressivoCentro().length() == 1) setProgressivoCentro("00".concat(getProgressivoCentro())); if (getProgressivoCentro() != null && getProgressivoCentro().length() == 2) setProgressivoCentro("0".concat(getProgressivoCentro())); } OrderProjectImportAdapter handle(final OrderProjectImportAdapter previousRow); String deriveOrderNumber(); void correctProgressivoCentroIfNecessary(); String deriveProjectReference(); @Override void handleRow(final OrderProjectImportAdapter previousRow); }### Answer: @Test public void appendsZerosToProgressivoCentro() throws Exception { OrderProjectImportAdapter adapter = new OrderProjectImportAdapter(); adapter.setProgressivoCentro("1"); assertThat(adapter.getProgressivoCentro()).isEqualTo("1"); adapter.correctProgressivoCentroIfNecessary(); assertThat(adapter.getProgressivoCentro()).isEqualTo("001"); adapter.setProgressivoCentro("11"); adapter.correctProgressivoCentroIfNecessary(); assertThat(adapter.getProgressivoCentro()).isEqualTo("011"); adapter.setProgressivoCentro("111"); adapter.correctProgressivoCentroIfNecessary(); assertThat(adapter.getProgressivoCentro()).isEqualTo("111"); }
### Question: OrderProjectImportAdapter implements FixtureAwareRowHandler<OrderProjectImportAdapter>, ExcelMetaDataEnabled { public String deriveProjectReference() { if (getCommessa() == null) return null; if (getCentro() == null) return ProjectImportAdapter.ITA_PROJECT_PREFIX + getCommessa(); return ProjectImportAdapter.deriveProjectReference(getCommessa()); } OrderProjectImportAdapter handle(final OrderProjectImportAdapter previousRow); String deriveOrderNumber(); void correctProgressivoCentroIfNecessary(); String deriveProjectReference(); @Override void handleRow(final OrderProjectImportAdapter previousRow); }### Answer: @Test public void deriveProjectNumberTest() { OrderProjectImportAdapter adapter = new OrderProjectImportAdapter(); adapter.setCommessa("106"); assertThat(adapter.deriveProjectReference()).isEqualTo("ITPR106"); }
### Question: ChamberOfCommerceCodeLookUpService { public List<OrganisationNameNumberViewModel> getChamberOfCommerceCodeCandidatesByOrganisation(final Organisation organisation) { return getChamberOfCommerceCodeCandidatesByOrganisation(organisation.getName(), organisation.getAtPath()); } List<OrganisationNameNumberViewModel> getChamberOfCommerceCodeCandidatesByOrganisation(final Organisation organisation); List<OrganisationNameNumberViewModel> getChamberOfCommerceCodeCandidatesByOrganisation(final String name, final String atPath); OrganisationNameNumberViewModel getChamberOfCommerceCodeCandidatesByCode(final Organisation organisation); OrganisationNameNumberViewModel getChamberOfCommerceCodeCandidatesByCode(final String code, final String atPath); static final List<String> LEGAL_FORMS; }### Answer: @Test public void getChamberOfCommerceCodeCandidatesByOrganisation_works() throws Exception { ChamberOfCommerceCodeLookUpService service = new ChamberOfCommerceCodeLookUpService(){ @Override List<OrganisationNameNumberViewModel> findCandidatesForFranceByName(final String name){ return Arrays.asList( new OrganisationNameNumberViewModel(), new OrganisationNameNumberViewModel(), new OrganisationNameNumberViewModel() ); } }; Organisation organisation = new Organisation(){ @Override public String getAtPath(){ return "/FRA"; } }; organisation.setName("Company"); List<OrganisationNameNumberViewModel> result = service.getChamberOfCommerceCodeCandidatesByOrganisation(organisation); Assertions.assertThat(result.size()).isEqualTo(3); }
### Question: ChamberOfCommerceCodeLookUpService { public OrganisationNameNumberViewModel getChamberOfCommerceCodeCandidatesByCode(final Organisation organisation) { return getChamberOfCommerceCodeCandidatesByCode(organisation.getChamberOfCommerceCode(), organisation.getAtPath()); } List<OrganisationNameNumberViewModel> getChamberOfCommerceCodeCandidatesByOrganisation(final Organisation organisation); List<OrganisationNameNumberViewModel> getChamberOfCommerceCodeCandidatesByOrganisation(final String name, final String atPath); OrganisationNameNumberViewModel getChamberOfCommerceCodeCandidatesByCode(final Organisation organisation); OrganisationNameNumberViewModel getChamberOfCommerceCodeCandidatesByCode(final String code, final String atPath); static final List<String> LEGAL_FORMS; }### Answer: @Test public void getChamberOfCommerceCodeCandidatesByCode_works() throws Exception { ChamberOfCommerceCodeLookUpService service = new ChamberOfCommerceCodeLookUpService(){ @Override OrganisationNameNumberViewModel findCandidateForFranceByCode(final String code){ return new OrganisationNameNumberViewModel(); } }; Organisation organisation = new Organisation(){ @Override public String getAtPath(){ return "/FRA"; } }; organisation.setName("Company"); OrganisationNameNumberViewModel result = service.getChamberOfCommerceCodeCandidatesByCode(organisation.getName(), organisation.getAtPath()); Assertions.assertThat(result).isNotNull(); }
### Question: ChargingLine implements Importable { boolean discardedOrAggregatedOrApplied() { if (getImportStatus() == ImportStatus.DISCARDED || getImportStatus() == ImportStatus.AGGREGATED || getApplied() != null) { return true; } return false; } ChargingLine(); String title(); @PropertyLayout(hidden = Where.PARENTED_TABLES) Lease getLease(); LeaseItem getLeaseItem(); @Action(semantics = SemanticsOf.NON_IDEMPOTENT) ImportStatus apply(); boolean hideApply(); @Action(semantics = SemanticsOf.IDEMPOTENT) ChargingLine discard(); boolean hideDiscard(); @Action(semantics = SemanticsOf.IDEMPOTENT) ChargingLine noUpdate(); boolean hideNoUpdate(); @Programmatic List<Object> importChargingLine(final boolean nonDiscardedOnly); @Override @Programmatic List<Object> importData(final Object previousRow); }### Answer: @Test public void discarded_or_applied() throws Exception { ChargingLine line = new ChargingLine(); Assertions.assertThat(line.discardedOrAggregatedOrApplied()).isFalse(); line.setImportStatus(ImportStatus.DISCARDED); Assertions.assertThat(line.discardedOrAggregatedOrApplied()).isTrue(); line.setImportStatus(ImportStatus.LEASE_ITEM_CREATED); Assertions.assertThat(line.discardedOrAggregatedOrApplied()).isFalse(); line.setImportStatus(null); line.setApplied(new LocalDate()); Assertions.assertThat(line.discardedOrAggregatedOrApplied()).isTrue(); line.setImportStatus(ImportStatus.LEASE_ITEM_CREATED); line.setApplied(new LocalDate()); Assertions.assertThat(line.discardedOrAggregatedOrApplied()).isTrue(); line.setImportStatus(ImportStatus.DISCARDED); line.setApplied(new LocalDate()); Assertions.assertThat(line.discardedOrAggregatedOrApplied()).isTrue(); }
### Question: ChamberOfCommerceCodeLookUpService { OrganisationNameNumberViewModel findCandidateForFranceByCode(final String code) { try { SirenResult sirenResult = sirenService.getCompanyName(code); if (sirenResult != null) { return new OrganisationNameNumberViewModel(sirenResult.getCompanyName(), code, sirenResult.getEntryDate()); } else { messageService.warnUser(NO_RESULTS_WARNING); } } catch (ClientProtocolException e) { messageService.warnUser(CONNECTION_WARNING); } return null; } List<OrganisationNameNumberViewModel> getChamberOfCommerceCodeCandidatesByOrganisation(final Organisation organisation); List<OrganisationNameNumberViewModel> getChamberOfCommerceCodeCandidatesByOrganisation(final String name, final String atPath); OrganisationNameNumberViewModel getChamberOfCommerceCodeCandidatesByCode(final Organisation organisation); OrganisationNameNumberViewModel getChamberOfCommerceCodeCandidatesByCode(final String code, final String atPath); static final List<String> LEGAL_FORMS; }### Answer: @Test public void find_Candidate_For_France_By_Code_works_when_no_result() throws Exception { ChamberOfCommerceCodeLookUpService service = new ChamberOfCommerceCodeLookUpService(); service.messageService = mockMessageService; service.sirenService = mockSirenService; String noResultsWarning = "A connection to the external Siren service could be made, but no results were returned"; context.checking(new Expectations(){{ oneOf(mockSirenService).getCompanyName("some cocc that returns no results"); will(returnValue(null)); allowing(mockMessageService).warnUser(noResultsWarning); }}); service.findCandidateForFranceByCode("some cocc that returns no results"); }
### Question: ChamberOfCommerceCodeLookUpService { String filterLegalFormsFromOrganisationName(final String name ) { return Arrays.stream(name.split(" ")) .filter(element -> !LEGAL_FORMS.contains(element)) .filter(element -> !LEGAL_FORMS.contains(element.replace(".", ""))) .collect(Collectors.joining(" ")); } List<OrganisationNameNumberViewModel> getChamberOfCommerceCodeCandidatesByOrganisation(final Organisation organisation); List<OrganisationNameNumberViewModel> getChamberOfCommerceCodeCandidatesByOrganisation(final String name, final String atPath); OrganisationNameNumberViewModel getChamberOfCommerceCodeCandidatesByCode(final Organisation organisation); OrganisationNameNumberViewModel getChamberOfCommerceCodeCandidatesByCode(final String code, final String atPath); static final List<String> LEGAL_FORMS; }### Answer: @Test public void filterLegalFormsFromOrganisationName_works() throws Exception { ChamberOfCommerceCodeLookUpService service = new ChamberOfCommerceCodeLookUpService(); final String legalForm_SA_without_occurrence_in_name_1 = "SA ACME"; final String legalForm_SA_without_occurrence_in_name_2 = "ACME SA"; final String legalForm_SA_without_occurrence_in_name_with_dots = "ACME S.A.S"; final String legalForm_SA_with_occurrence_in_name = "SACME SA"; Assertions.assertThat(service.filterLegalFormsFromOrganisationName(legalForm_SA_without_occurrence_in_name_1)).isEqualTo("ACME"); Assertions.assertThat(service.filterLegalFormsFromOrganisationName(legalForm_SA_without_occurrence_in_name_2)).isEqualTo("ACME"); Assertions.assertThat(service.filterLegalFormsFromOrganisationName(legalForm_SA_without_occurrence_in_name_with_dots)).isEqualTo("ACME"); Assertions.assertThat(service.filterLegalFormsFromOrganisationName(legalForm_SA_with_occurrence_in_name)).isEqualTo("SACME"); }
### Question: StatusMessageSummaryCache implements WithTransactionScope { @Programmatic public StatusMessageSummary findFor(final InvoiceForLease invoice) { final Long invoiceId = idFor(invoice); if (invoiceId==null) return null; Optional<StatusMessageSummary> statusMessageOpt = statusMessageByInvoiceId.get(invoiceId); if (statusMessageOpt == null) { final List<InvoiceIdAndStatusMessageSummary> statusMessages = find(invoiceId); final Map<Long, Optional<StatusMessageSummary>> map = statusMessages.stream() .collect(Collectors.toMap( InvoiceIdAndStatusMessageSummary::getInvoiceId, StatusMessageSummaryCache::optionallyRecreateFrom)); statusMessageByInvoiceId.putAll(map); statusMessageOpt = statusMessageByInvoiceId.get(invoiceId); } return statusMessageOpt.orElse(null); } @Programmatic StatusMessageSummary findFor(final InvoiceForLease invoice); @Override void resetForNextTransaction(); }### Answer: @Test public void findFor() { StatusMessageSummaryCache service = new StatusMessageSummaryCache(){ Long idFor(final Object object) { return null; }; }; InvoiceForLease invoice = new InvoiceForLease(); Assertions.assertThat(service.findFor(invoice)).isNull(); }
### Question: RendererForStringInterpolatorCaptureUrl implements RendererFromCharsToBytes { protected URL previewCharsToBytes( final DocumentType documentType, final String atPath, final long templateVersion, final String templateChars, final Object dataModel) throws IOException { final StringInterpolatorService.Root root = (StringInterpolatorService.Root) dataModel; final String urlStr = stringInterpolator.interpolate(root, templateChars); return new URL(urlStr); } @Override byte[] renderCharsToBytes( final DocumentType documentType, final String variant, final String atPath, final long templateVersion, final String templateChars, final Object dataModel); }### Answer: @Test public void previewCharsToBytes() throws Exception { final String urlStr = "http: final URL url = new URL(urlStr); final String externalForm = url.toExternalForm(); Assertions.assertThat(externalForm).isEqualTo(urlStr); }
### Question: ChargingLine implements Importable { @Action(semantics = SemanticsOf.NON_IDEMPOTENT) public ImportStatus apply() { if (!discardedOrAggregatedOrApplied()) { ImportStatus result = fastnetImportService.updateOrCreateItemAndTerm(this); if (result != null && getImportStatus() != ImportStatus.AGGREGATED) { setApplied(clockService.now()); setImportStatus(result); } return result; } else { return getImportStatus(); } } ChargingLine(); String title(); @PropertyLayout(hidden = Where.PARENTED_TABLES) Lease getLease(); LeaseItem getLeaseItem(); @Action(semantics = SemanticsOf.NON_IDEMPOTENT) ImportStatus apply(); boolean hideApply(); @Action(semantics = SemanticsOf.IDEMPOTENT) ChargingLine discard(); boolean hideDiscard(); @Action(semantics = SemanticsOf.IDEMPOTENT) ChargingLine noUpdate(); boolean hideNoUpdate(); @Programmatic List<Object> importChargingLine(final boolean nonDiscardedOnly); @Override @Programmatic List<Object> importData(final Object previousRow); }### Answer: @Test public void apply_discarded_works() throws Exception { ChargingLine line = new ChargingLine(); line.setApplied(new LocalDate()); line.setImportStatus(ImportStatus.LEASE_ITEM_CREATED); Assertions.assertThat(line.apply()).isEqualTo(ImportStatus.LEASE_ITEM_CREATED); }
### Question: ChargingLine implements Importable { void appendImportLog(final String msg){ final String prefix = clockService.nowAsLocalDateTime().toString("yyyy-MM-dd HH:mm:ss") + " "; String nwContent = prefix; if (getImportLog()!=null) { nwContent = nwContent.concat(msg).concat(" ").concat(getImportLog()); } else { nwContent = nwContent.concat(msg); } if (nwContent.length()>254) { nwContent = nwContent.substring(0,254); } setImportLog(nwContent); } ChargingLine(); String title(); @PropertyLayout(hidden = Where.PARENTED_TABLES) Lease getLease(); LeaseItem getLeaseItem(); @Action(semantics = SemanticsOf.NON_IDEMPOTENT) ImportStatus apply(); boolean hideApply(); @Action(semantics = SemanticsOf.IDEMPOTENT) ChargingLine discard(); boolean hideDiscard(); @Action(semantics = SemanticsOf.IDEMPOTENT) ChargingLine noUpdate(); boolean hideNoUpdate(); @Programmatic List<Object> importChargingLine(final boolean nonDiscardedOnly); @Override @Programmatic List<Object> importData(final Object previousRow); }### Answer: @Test public void append_import_log_works() throws Exception { ChargingLine line = new ChargingLine(); line.clockService = mockClockService; line.setImportLog("first message"); context.checking(new Expectations(){{ allowing(mockClockService).nowAsLocalDateTime(); will(returnValue(LocalDateTime.parse("2018-01-01"))); }}); line.appendImportLog("second message"); Assertions.assertThat(line.getImportLog()).isEqualTo("2018-01-01 00:00:00 second message first message"); String stringOf254Chars = ""; for (int i=0; i<254; i++ ){ stringOf254Chars = stringOf254Chars.concat("X"); } line.setImportLog(stringOf254Chars); Assertions.assertThat(line.getImportLog().length()).isEqualTo(254); line.appendImportLog("second message"); Assertions.assertThat(line.getImportLog().length()).isEqualTo(254); Assertions.assertThat(line.getImportLog()).startsWith("2018-01-01 00:00:00 second message XXX"); line.setImportLog(null); line.appendImportLog("some message"); Assertions.assertThat(line.getImportLog()).isEqualTo("2018-01-01 00:00:00 some message"); }
### Question: RentRollLine implements Importable { String keyToLeaseExternalReference() { return getKontraktNr() != null ? getKontraktNr().substring(2) : null; } RentRollLine(); String title(); LocalDate getInflyttningsDatumAsDate(); @Action(semantics = SemanticsOf.SAFE) List<ChargingLine> getChargingLines(); @PropertyLayout(hidden = Where.PARENTED_TABLES) Lease getLease(); @Action(semantics = SemanticsOf.NON_IDEMPOTENT, associateWith = "chargingLines", associateWithSequence = "1") RentRollLine apply(List<ChargingLine> lines); @Action(semantics = SemanticsOf.NON_IDEMPOTENT, associateWith = "chargingLines", associateWithSequence = "2") RentRollLine discard(List<ChargingLine> lines); @Override @Programmatic List<Object> importData(final Object previousRow); }### Answer: @Test public void keyToLeaseExternalReference_works_when_not_null() throws Exception { RentRollLine line = new RentRollLine(); line.setKontraktNr("351234-5678-01"); Assertions.assertThat(line.keyToLeaseExternalReference()).isEqualTo("1234-5678-01"); } @Test public void keyToLeaseExternalReference_works_when_null() throws Exception { RentRollLine line = new RentRollLine(); Assertions.assertThat(line.keyToLeaseExternalReference()).isNull(); }
### Question: TurnoverAggregation { @Programmatic public LocalDateInterval calculationPeriod(){ return LocalDateInterval.including(getDate().minusMonths(23), getDate()); } TurnoverAggregation(); TurnoverAggregation(final TurnoverReportingConfig turnoverReportingConfig, final LocalDate date, final Currency currency); String title(); @Programmatic void remove(); @Programmatic LocalDateInterval calculationPeriod(); @Programmatic List<TurnoverAggregateForPeriod> aggregatesForPeriod(); @Programmatic List<PurchaseCountAggregateForPeriod> purchaseCountAggregatesForPeriod(); @Persistent(table="AggregationsTurnovers") @Join(column="aggregationId") @Element(column="turnoverId") @Getter @Setter public Set<Turnover> turnovers; }### Answer: @Test public void calculationPeriod_works() { TurnoverAggregation aggregation = new TurnoverAggregation(); final LocalDate aggregationDate = new LocalDate(2020, 1, 1); aggregation.setDate(aggregationDate); Assertions.assertThat(aggregation.calculationPeriod().toString()).isEqualTo("2018-02-01/2020-01-02"); Assertions.assertThat(aggregation.calculationPeriod().endDate()).isEqualTo(aggregationDate); }
### Question: ContextFilter implements Filter { public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { Map<String, String> attachments = setCallChainContextMap(invocation); if (attachments != null) { attachments = new HashMap<String, String>(attachments); attachments.remove(Constants.PATH_KEY); attachments.remove(Constants.GROUP_KEY); attachments.remove(Constants.VERSION_KEY); attachments.remove(Constants.DUBBO_VERSION_KEY); attachments.remove(Constants.TOKEN_KEY); attachments.remove(Constants.TIMEOUT_KEY); } RpcContext.getContext() .setInvoker(invoker) .setInvocation(invocation) .setLocalAddress(invoker.getUrl().getHost(), invoker.getUrl().getPort()); if (attachments != null) { if (RpcContext.getContext().getAttachments() != null) { RpcContext.getContext().getAttachments().putAll(attachments); } else { RpcContext.getContext().setAttachments(attachments); } } if (invocation instanceof RpcInvocation) { ((RpcInvocation) invocation).setInvoker(invoker); } try { return invoker.invoke(invocation); } finally { RpcContext.removeContext(); } } Result invoke(Invoker<?> invoker, Invocation invocation); }### Answer: @SuppressWarnings("unchecked") @Test public void testSetContext() { invocation = EasyMock.createMock(Invocation.class); EasyMock.expect(invocation.getMethodName()).andReturn("$enumlength").anyTimes(); EasyMock.expect(invocation.getParameterTypes()).andReturn(new Class<?>[] { Enum.class }).anyTimes(); EasyMock.expect(invocation.getArguments()).andReturn(new Object[] { "hello" }).anyTimes(); EasyMock.expect(invocation.getAttachments()).andReturn(null).anyTimes(); EasyMock.replay(invocation); invoker = EasyMock.createMock(Invoker.class); EasyMock.expect(invoker.isAvailable()).andReturn(true).anyTimes(); EasyMock.expect(invoker.getInterface()).andReturn(DemoService.class).anyTimes(); RpcResult result = new RpcResult(); result.setValue("High"); EasyMock.expect(invoker.invoke(invocation)).andReturn(result).anyTimes(); URL url = URL.valueOf("test: EasyMock.expect(invoker.getUrl()).andReturn(url).anyTimes(); EasyMock.replay(invoker); contextFilter.invoke(invoker, invocation); assertNull(RpcContext.getContext().getInvoker()); } @Test public void testWithAttachments() { URL url = URL.valueOf("test: Invoker<DemoService> invoker = new MyInvoker<DemoService>(url); Invocation invocation = new MockInvocation(); Result result = contextFilter.invoke(invoker, invocation); assertNull(RpcContext.getContext().getInvoker()); }
### Question: Generators { protected Map<Matcher<ASTType>, ReadWriteGenerator> getGenerators() { return generators; } Generators(ASTClassFactory astClassFactory); boolean matches(ASTType type); ReadWriteGenerator getGenerator(ASTType type); void addPair(Class clazz, String readMethod, String writeMethod); void addPair(Class clazz, String readMethod, String writeMethod, Class writeParam); void addPair(String clazzName, String readMethod, String writeMethod); void addPair(String clazzName, String readMethod, String writeMethod, String writeParam); void addPair(ASTType type, String readMethod, String writeMethod, String writeParam); void addPair(Class clazz, ReadWriteGenerator generator); void addPair(ASTType type, ReadWriteGenerator generator); void add(Matcher<ASTType> matcher, ReadWriteGenerator generator); }### Answer: @Test public void testParcelMethodUsage() throws NoSuchMethodException { for (Map.Entry<Matcher<ASTType>, ReadWriteGenerator> entry : ((Generators)generators).getGenerators().entrySet()) { if(entry.getValue() instanceof ReadWriteGeneratorBase){ ReadWriteGeneratorBase readWriteGeneratorBase = (ReadWriteGeneratorBase)entry.getValue(); Method readMethod = Parcel.class.getMethod(readWriteGeneratorBase.getReadMethod(), readWriteGeneratorBase.getReadMethodParams()); assertNotNull(readMethod); Method writeMethod = Parcel.class.getMethod(readWriteGeneratorBase.getWriteMethod(), readWriteGeneratorBase.getWriteMethodParams()); assertNotNull(writeMethod); } } }
### Question: SpringSkillsAutoConfiguration { @Bean @ConditionalOnMissingBean(value=SpeechRequestDispatcher.class) public SpeechRequestDispatcher dispatcher() { return new BeanNameSpeechRequestDispatcher( (request) -> { Speech speech = new Speech(); speech.setSsml("<speak>I don't know what you're doing...</speak>"); SpeechCard card = new SpeechCard("Unknown", "Unknown intent"); SpeechResponse response = new SpeechResponse(speech, card); response.setEndSession(false); return response; }, (request) -> { Speech speech = new Speech(); speech.setSsml("<speak>Welcome</speak>"); SpeechCard card = new SpeechCard("Welcome", "Welcome"); SpeechResponse response = new SpeechResponse(speech, card); response.setEndSession(false); return response; }, new SessionEndedSpeechRequestHandler() { @Override public void handleSessionEndedRequest(SessionEndedSpeechRequest request) { logger.info("Session ended. Reason: " + request.getReason()); } }); } @Bean @ConditionalOnMissingBean(value=SpeechRequestDispatcher.class) SpeechRequestDispatcher dispatcher(); }### Answer: @Test public void shouldAutoConfigureSpringSkills() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) .run( context -> { assertThat(context).hasSingleBean(SpeechRequestDispatcher.class); assertThat(context.getBean(SpeechRequestDispatcher.class)) .isSameAs(context.getBean(SpringSkillsAutoConfiguration.class).dispatcher()); }); } @Test public void shouldBackoffOnSpeechRequestDispatcherConfiguration() { this.contextRunner.withUserConfiguration(SpeechRequestDispatcherConfiguration.class) .run( context -> { assertThat(context).hasSingleBean(SpeechRequestDispatcher.class); assertThat(context.getBean(SpeechRequestDispatcher.class)) .isSameAs(context.getBean(SpeechRequestDispatcherConfiguration.class).dispatcher()); }); }
### Question: GoogleAssistantAutoConfiguration { @Bean @ConditionalOnMissingBean(WebhookController.class) public WebhookController webhookController(SpeechRequestDispatcher dispatcher) { return new WebhookController(dispatcher); } @Bean @ConditionalOnMissingBean(WebhookController.class) WebhookController webhookController(SpeechRequestDispatcher dispatcher); }### Answer: @Test public void shouldAutoConfigureAlexaBeans() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) .run( context -> { SpeechRequestDispatcher dispatcher = context.getBean(SpeechRequestDispatcher.class); assertThat(context).hasSingleBean(WebhookController.class); assertThat(context.getBean(WebhookController.class)) .isSameAs(context.getBean(GoogleAssistantAutoConfiguration.class).webhookController(dispatcher)); }); } @Test public void shouldBackOffOnAutoConfiguredAlexaBeans() { this.contextRunner.withUserConfiguration(GoogleConfiguration.class) .run( context -> { SpeechRequestDispatcher dispatcher = context.getBean(SpeechRequestDispatcher.class); assertThat(context).hasSingleBean(WebhookController.class); assertThat(context.getBean(WebhookController.class)) .isSameAs(context.getBean(GoogleConfiguration.class).webhookController(dispatcher)); }); }
### Question: Hello { public String say() { return hello; } Hello(String s); String say(); }### Answer: @Test public void shouldSayHello() throws InterruptedException { assertEquals("hi", new Hello("hi").say()); Thread.sleep(1000); }
### Question: AppConfiguration { public String getString(final String propertyName) { if(this.javaSystemConfig.containsKey(propertyName)) { return this.javaSystemConfig.getString(propertyName); } List<String> propertiesToAttempt = getOrderedPropertyList(propertyName); for (String propertyToAttempt : propertiesToAttempt) { if (this.serviceConfig.containsKey(propertyToAttempt)) { return this.serviceConfig.getString(propertyToAttempt); } } log.warn("No value found for property named \"" + propertyName + "\""); return null; } private AppConfiguration(); boolean isCronConnector(); void initialize(final boolean isRunningCmdLine, final String connectorType, final String projectName); void clear(); boolean hasProperty(final String propertyName); String getString(final String propertyName); String getString(final String propertyName, final String defaultValue); String[] getList(final String propertyName); String[] getList(final String propertyName, final String[] defaultValue); long getLong(final String propertyName); long getLong(final String propertyName, final long defaultValue); int getInt(final String propertyName); int getInt(final String propertyName, final int defaultValue); float getFloat(final String propertyName); float getFloat(final String propertyName, final float defaultValue); double getDouble(final String propertyName); double getDouble(final String propertyName, final double defaultValue); boolean getBoolean(final String propertyName); boolean getBoolean(final String propertyName, final boolean defaultValue); AWSCredentialsProvider getCredentialsProvider(); boolean isRunningCmdLine(); String getConnectorType(); String getProjectName(); HealthCheckController getHealthCheckController(); void setHealthCheckController(final HealthCheckController healthCheckController); static final AppConfiguration INSTANCE; }### Answer: @Test public void testOverrides() { Assert.assertEquals("value1", AppConfiguration.INSTANCE.getString("property_a")); Assert.assertEquals("value2", AppConfiguration.INSTANCE.getString("property_b")); Assert.assertEquals("value3", AppConfiguration.INSTANCE.getString("property_c")); Assert.assertEquals("value4", AppConfiguration.INSTANCE.getString("property_d")); Assert.assertEquals("value5", AppConfiguration.INSTANCE.getString("property_e")); Assert.assertEquals("value6", AppConfiguration.INSTANCE.getString("property_f")); }
### Question: HexUtil { public static String toHexFromByte(final byte b) { byte leftSymbol = (byte) ((b >>> BITS_PER_HEX_DIGIT) & 0x0f); byte rightSymbol = (byte) (b & 0x0f); return (hexSymbols[leftSymbol] + hexSymbols[rightSymbol]); } static String toHexFromByte(final byte b); static byte toByteFromHex(char upperChar, char lowerChar); static String toHexFromBytes(final ByteBuffer bytes); static String toHexFromBytes(final byte[] bytes); static byte[] toBytesFromHex(String hexStr); final static int BITS_PER_HEX_DIGIT; }### Answer: @Test public void testHexToByte() { Assert.assertEquals("00", HexUtil.toHexFromByte((byte)0x00)); Assert.assertEquals("01", HexUtil.toHexFromByte((byte)0x01)); Assert.assertEquals("02", HexUtil.toHexFromByte((byte)0x02)); Assert.assertEquals("03", HexUtil.toHexFromByte((byte)0x03)); Assert.assertEquals("04", HexUtil.toHexFromByte((byte)0x04)); Assert.assertEquals("05", HexUtil.toHexFromByte((byte)0x05)); Assert.assertEquals("06", HexUtil.toHexFromByte((byte)0x06)); Assert.assertEquals("07", HexUtil.toHexFromByte((byte)0x07)); Assert.assertEquals("08", HexUtil.toHexFromByte((byte)0x08)); Assert.assertEquals("09", HexUtil.toHexFromByte((byte)0x09)); Assert.assertEquals("0a", HexUtil.toHexFromByte((byte)0x0a)); Assert.assertEquals("0b", HexUtil.toHexFromByte((byte)0x0b)); Assert.assertEquals("0c", HexUtil.toHexFromByte((byte)0x0c)); Assert.assertEquals("0d", HexUtil.toHexFromByte((byte)0x0d)); Assert.assertEquals("0e", HexUtil.toHexFromByte((byte)0x0e)); Assert.assertEquals("0f", HexUtil.toHexFromByte((byte)0x0f)); Assert.assertEquals("23", HexUtil.toHexFromByte((byte)0x23)); Assert.assertEquals("19", HexUtil.toHexFromByte((byte)0x19)); Assert.assertEquals("75", HexUtil.toHexFromByte((byte)0x75)); Assert.assertEquals("43", HexUtil.toHexFromByte((byte)0x43)); Assert.assertEquals("a9", HexUtil.toHexFromByte((byte)0xa9)); Assert.assertEquals("3b", HexUtil.toHexFromByte((byte)0x3b)); Assert.assertEquals("c3", HexUtil.toHexFromByte((byte)0xc3)); Assert.assertEquals("ff", HexUtil.toHexFromByte((byte)0xff)); }
### Question: HexUtil { public static byte toByteFromHex(char upperChar, char lowerChar) { byte upper = HEX_TO_BYTE_MAP.get(Character.toLowerCase(upperChar)); byte lower = HEX_TO_BYTE_MAP.get(Character.toLowerCase(lowerChar)); return (byte) ((upper << BITS_PER_HEX_DIGIT) + lower); } static String toHexFromByte(final byte b); static byte toByteFromHex(char upperChar, char lowerChar); static String toHexFromBytes(final ByteBuffer bytes); static String toHexFromBytes(final byte[] bytes); static byte[] toBytesFromHex(String hexStr); final static int BITS_PER_HEX_DIGIT; }### Answer: @Test public void testByteToHex() { Assert.assertEquals((byte)0x00, HexUtil.toByteFromHex('0','0')); Assert.assertEquals((byte)0x01, HexUtil.toByteFromHex('0','1')); Assert.assertEquals((byte)0x02, HexUtil.toByteFromHex('0','2')); Assert.assertEquals((byte)0x03, HexUtil.toByteFromHex('0','3')); Assert.assertEquals((byte)0x04, HexUtil.toByteFromHex('0','4')); Assert.assertEquals((byte)0x05, HexUtil.toByteFromHex('0','5')); Assert.assertEquals((byte)0x06, HexUtil.toByteFromHex('0','6')); Assert.assertEquals((byte)0x07, HexUtil.toByteFromHex('0','7')); Assert.assertEquals((byte)0x08, HexUtil.toByteFromHex('0','8')); Assert.assertEquals((byte)0x09, HexUtil.toByteFromHex('0','9')); Assert.assertEquals((byte)0x0a, HexUtil.toByteFromHex('0','a')); Assert.assertEquals((byte)0x0b, HexUtil.toByteFromHex('0','b')); Assert.assertEquals((byte)0x0c, HexUtil.toByteFromHex('0','c')); Assert.assertEquals((byte)0x0d, HexUtil.toByteFromHex('0','d')); Assert.assertEquals((byte)0x0e, HexUtil.toByteFromHex('0','e')); Assert.assertEquals((byte)0x0f, HexUtil.toByteFromHex('0','f')); Assert.assertEquals((byte)0x23, HexUtil.toByteFromHex('2','3')); Assert.assertEquals((byte)0x19, HexUtil.toByteFromHex('1','9')); Assert.assertEquals((byte)0x75, HexUtil.toByteFromHex('7','5')); Assert.assertEquals((byte)0x43, HexUtil.toByteFromHex('4','3')); Assert.assertEquals((byte)0xa9, HexUtil.toByteFromHex('a','9')); Assert.assertEquals((byte)0x3b, HexUtil.toByteFromHex('3','b')); Assert.assertEquals((byte)0xc3, HexUtil.toByteFromHex('c','3')); Assert.assertEquals((byte)0xff, HexUtil.toByteFromHex('f','f')); }
### Question: HexUtil { public static String toHexFromBytes(final ByteBuffer bytes) { if (bytes == null) { return ""; } StringBuilder hexBuffer = new StringBuilder(); while (bytes.hasRemaining()) { hexBuffer.append(toHexFromByte(bytes.get())); } return hexBuffer.toString(); } static String toHexFromByte(final byte b); static byte toByteFromHex(char upperChar, char lowerChar); static String toHexFromBytes(final ByteBuffer bytes); static String toHexFromBytes(final byte[] bytes); static byte[] toBytesFromHex(String hexStr); final static int BITS_PER_HEX_DIGIT; }### Answer: @Test public void testHexToBytes() { byte[] bytes = { (byte)0x0a, (byte)0xff, (byte)0x12, (byte)0x38, (byte)0xde, (byte)0xad, (byte)0xbe, (byte)0xef, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0xde, (byte)0xad, (byte)0xc0, (byte)0xde }; Assert.assertEquals("0aff1238deadbeef00000000deadc0de", HexUtil.toHexFromBytes(bytes)); Assert.assertEquals("", HexUtil.toHexFromBytes(new byte[] {})); Assert.assertEquals("", HexUtil.toHexFromBytes((byte[])null)); Assert.assertEquals("01", HexUtil.toHexFromBytes(new byte[] { (byte) 0x01 })); ByteBuffer bb = ByteBuffer.wrap(bytes); Assert.assertEquals("0aff1238deadbeef00000000deadc0de", HexUtil.toHexFromBytes(bb)); Assert.assertEquals("", HexUtil.toHexFromBytes(ByteBuffer.wrap(new byte[] {}))); Assert.assertEquals("", HexUtil.toHexFromBytes((ByteBuffer)null)); Assert.assertEquals("01", HexUtil.toHexFromBytes(ByteBuffer.wrap(new byte[] { (byte) 0x01 }))); }
### Question: HexUtil { public static byte[] toBytesFromHex(String hexStr) { if (hexStr == null || hexStr.length() == 0) { return new byte[] {}; } if (hexStr.length() % 2 != 0) { hexStr += '0'; } int byteIndex = 0; final byte[] bytes = new byte[hexStr.length() / 2]; for (int i = 0; i < hexStr.length(); i += 2) { char upper = hexStr.charAt(i); char lower = hexStr.charAt(i + 1); bytes[byteIndex] = toByteFromHex(upper, lower); byteIndex++; } return bytes; } static String toHexFromByte(final byte b); static byte toByteFromHex(char upperChar, char lowerChar); static String toHexFromBytes(final ByteBuffer bytes); static String toHexFromBytes(final byte[] bytes); static byte[] toBytesFromHex(String hexStr); final static int BITS_PER_HEX_DIGIT; }### Answer: @Test public void testBytesToHex() { byte[] bytes = { (byte)0x0a, (byte)0xff, (byte)0x12, (byte)0x38, (byte)0xde, (byte)0xad, (byte)0xbe, (byte)0xef, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0xde, (byte)0xad, (byte)0xc0, (byte)0xde }; String hex = "0aff1238deadbeef00000000deadc0de"; Assert.assertTrue(Arrays.equals(bytes, HexUtil.toBytesFromHex(hex))); hex = "54321"; Assert.assertTrue(Arrays.equals(new byte[] { (byte)0x54, (byte)0x32, (byte)0x10 }, HexUtil.toBytesFromHex(hex))); hex = "a"; Assert.assertTrue(Arrays.equals(new byte[] { (byte)0xa0 }, HexUtil.toBytesFromHex(hex))); Assert.assertTrue(Arrays.equals(new byte[] { }, HexUtil.toBytesFromHex(""))); Assert.assertTrue(Arrays.equals(new byte[] { }, HexUtil.toBytesFromHex(null))); }
### Question: DecoderUtil { public static String getUtf8FromByteBuffer(final ByteBuffer bb) { bb.rewind(); byte[] bytes; if (bb.hasArray()) { bytes = bb.array(); } else { bytes = new byte[bb.remaining()]; bb.get(bytes); } return new String(bytes, StandardCharsets.UTF_8); } static String getUtf8FromByteBuffer(final ByteBuffer bb); }### Answer: @Test public void testDecode() { String testString = "asdlkfjajo3wjaf3o8ajlfija3lfijaslijfl83auj"; byte[] encodedBytes = testString.getBytes(StandardCharsets.UTF_8); ByteBuffer bb = ByteBuffer.wrap(encodedBytes); String decodedString = DecoderUtil.getUtf8FromByteBuffer(bb); Assert.assertEquals(testString, decodedString); }
### Question: KinesisEvent { public Long getServerTimestamp() { return serverTimestamp; } KinesisEvent(); void parseFromJson(final ObjectMapper jsonParser, final String rawJson); String getRawJson(); String getProcessedJson(); @Override String toString(); boolean isRequiredSanitization(); List<String> getSanitizedFields(); String getAppName(); void setAppName(String appName); String getAppVersion(); void setAppVersion(String appVersion); String getEventVersion(); void setEventVersion(String eventVersion); String getEventId(); void setEventId(String eventId); String getEventType(); void setEventType(String eventType); Long getEventTimestamp(); void setEventTimestamp(Long eventTimestamp); String getClientId(); void setClientId(String clientId); String getLevelId(); void setLevelId(String levelId); Double getPositionX(); void setPositionX(Double positionX); Double getPositionY(); void setPositionY(Double positionY); String getShardId(); void setShardId(String shardId); String getPartitionKey(); void setPartitionKey(String partitionKey); String getSequenceNumber(); void setSequenceNumber(String sequenceNumber); Long getServerTimestamp(); void setServerTimestamp(Long serverArrivalTimestamp); static final String APP_NAME_JSON_KEY; static final String APP_VERSION_JSON_KEY; static final String EVENT_VERSION_JSON_KEY; static final String EVENT_ID_JSON_KEY; static final String EVENT_TYPE_JSON_KEY; static final String EVENT_TIMESTAMP_JSON_KEY; static final String CLIENT_ID_JSON_KEY; static final String LEVEL_ID_JSON_KEY; static final String POSITION_X_JSON_KEY; static final String POSITION_Y_JSON_KEY; static final String SERVER_TIMESTAMP_JSON_KEY; static final int APP_NAME_MAX_LENGTH; static final int APP_VERSION_MAX_LENGTH; static final int EVENT_VERSION_MAX_LENGTH; static final int EVENT_ID_MAX_LENGTH; static final int EVENT_TYPE_MAX_LENGTH; static final int CLIENT_ID_MAX_LENGTH; static final int LEVEL_ID_MAX_LENGTH; static final String RESTRICTED_CHARSET_REGEX; static final Pattern RESTRICTED_CHARSET; }### Answer: @Test public void testEnrichment() { String sampleEvent = "{\"event_version\":\"1.0\"," + "\"position_x\":556," + "\"app_name\":\"SampleGame\"," + "\"client_id\":\"d57faa2b-9bfd-4502-a7b7-a43cb365f8f2\"," + "\"position_y\":521," + "\"event_id\":\"91650ce5-825a-4e90-ab22-174a4fb2da79\"," + "\"level_id\":\"test_level\"," + "\"app_version\":\"1.0.0\"," + "\"event_timestamp\":1508872163135," + "\"event_type\":\"test_event\"}"; KinesisEvent event = parseEventEnforceSuccess(sampleEvent); JsonNode jsonRoot = eventProcessedJsonToJsonNode(event); Assert.assertNotNull(jsonRoot.get(KinesisEvent.SERVER_TIMESTAMP_JSON_KEY)); Assert.assertEquals(event.getServerTimestamp().longValue(), jsonRoot.get(KinesisEvent.SERVER_TIMESTAMP_JSON_KEY).asLong()); }
### Question: QueueBuffer { public synchronized void add(Message message) { linkLast(message); postProcessDeliverableNode(); } QueueBuffer(int inMemoryLimit, int indelibleMessageLimit, MessageReader messageReader); synchronized void add(Message message); synchronized void addAllBareMessages(Collection<Message> messages); synchronized void addBareMessage(Message message); synchronized boolean addIndelibleMessage(Message message); synchronized void remove(long messageId); synchronized void removeAll(Collection<DetachableMessage> messages); int size(); int getNumberOfInflightMessages(); int getNumberOfUndeliveredMessages(); synchronized Message getFirstDeliverable(); void markMessageFilled(Message message); void markMessageFillFailed(Message message); synchronized int clear(Consumer<Message> postDeleteAction); }### Answer: @Test public void testAdd() { QueueBuffer queueBuffer = new QueueBuffer(10, 0, messageReader); for (int i = 0; i < 10; i++) { Message message = new Message(i + 1, mockMetadata); queueBuffer.add(message); Assert.assertNotNull(message.getMetadata(), "Message data should not be cleared until the in-memory " + "limit is reached"); } for (int i = 0; i < 3; i++) { Message message = new Message(i + 1, mockMetadata); queueBuffer.add(message); Assert.assertNull(message.getMetadata(), "Message data should be cleared when the queue limit is reached"); } }
### Question: AuthResourceInMemoryDao implements AuthResourceDao { @Override public List<AuthResource> readAll(String resourceType, String ownerId) { Map<String, AuthResource> resourceMap = inMemoryResourceMap.row(resourceType); if (Objects.nonNull(resourceMap)) { Collection<AuthResource> authResources = resourceMap.values(); return authResources.stream() .filter(authResource -> authResource.getOwner().equals(ownerId)) .collect(Collectors.toList()); } return Collections.emptyList(); } @Override void persist(AuthResource authResource); @Override void update(AuthResource authResource); @Override boolean delete(String resourceType, String resource); @Override AuthResource read(String resourceType, String resource); @Override List<AuthResource> readAll(String resourceType, String ownerId); @Override List<AuthResource> readAll(String resourceType, String action, String ownerId, List<String> userGroups); @Override boolean isExists(String resourceType, String resourceName); @Override boolean updateOwner(String resourceType, String resourceName, String newOwner); @Override boolean addGroups(String resourceType, String resourceName, String action, List<String> groups); @Override boolean removeGroup(String resourceType, String resourceName, String action, String group); }### Answer: @Test(priority = 1) public void testReadAllByGroups() throws AuthServerException { List<AuthResource> exchanges = authResourceDao.readAll(ResourceType.EXCHANGE.toString(), "bind", "customer", Collections.singletonList("developer")); List<AuthResource> queues = authResourceDao.readAll(ResourceType.QUEUE.toString(), "bind", "customer", Arrays.asList("architect", "designer")); Assert.assertEquals(exchanges.size(), 1); Assert.assertEquals(queues.size(), 1); } @Test(priority = 1) public void testReadAll() throws AuthServerException { List<AuthResource> customer = authResourceDao.readAll(ResourceType.QUEUE.toString(), "customer"); List<AuthResource> customerExchange = authResourceDao.readAll(ResourceType.EXCHANGE.toString(), "customer"); List<AuthResource> manager = authResourceDao.readAll(ResourceType.EXCHANGE.toString(), "manager"); List<AuthResource> developer = authResourceDao.readAll(ResourceType.EXCHANGE.toString(), "developer"); Assert.assertEquals(customer.size(), 1); Assert.assertEquals(customerExchange.size(), 0); Assert.assertEquals(manager.size(), 2); Assert.assertEquals(developer.size(), 0); }
### Question: AuthResourceInMemoryDao implements AuthResourceDao { @Override public boolean isExists(String resourceType, String resourceName) { return inMemoryResourceMap.contains(resourceType, resourceName); } @Override void persist(AuthResource authResource); @Override void update(AuthResource authResource); @Override boolean delete(String resourceType, String resource); @Override AuthResource read(String resourceType, String resource); @Override List<AuthResource> readAll(String resourceType, String ownerId); @Override List<AuthResource> readAll(String resourceType, String action, String ownerId, List<String> userGroups); @Override boolean isExists(String resourceType, String resourceName); @Override boolean updateOwner(String resourceType, String resourceName, String newOwner); @Override boolean addGroups(String resourceType, String resourceName, String action, List<String> groups); @Override boolean removeGroup(String resourceType, String resourceName, String action, String group); }### Answer: @Test(priority = 1) public void testIsExists() throws AuthServerException { boolean queue1 = authResourceDao.isExists(ResourceType.QUEUE.toString(), "queue1"); boolean queue11 = authResourceDao.isExists(ResourceType.QUEUE.toString(), "queue11"); Assert.assertEquals(queue1, true); Assert.assertEquals(queue11, false); }
### Question: AuthResourceInMemoryDao implements AuthResourceDao { @Override public void update(AuthResource authResource) { inMemoryResourceMap.put(authResource.getResourceType(), authResource.getResourceName(), authResource); } @Override void persist(AuthResource authResource); @Override void update(AuthResource authResource); @Override boolean delete(String resourceType, String resource); @Override AuthResource read(String resourceType, String resource); @Override List<AuthResource> readAll(String resourceType, String ownerId); @Override List<AuthResource> readAll(String resourceType, String action, String ownerId, List<String> userGroups); @Override boolean isExists(String resourceType, String resourceName); @Override boolean updateOwner(String resourceType, String resourceName, String newOwner); @Override boolean addGroups(String resourceType, String resourceName, String action, List<String> groups); @Override boolean removeGroup(String resourceType, String resourceName, String action, String group); }### Answer: @Test(priority = 2) public void testUpdate() throws AuthServerException { Map<String, Set<String>> actionsUserGroupsMap = new HashMap<>(); actionsUserGroupsMap.put("publish", new HashSet<>(Arrays.asList("architect", "customer", "manager"))); AuthResource exchange = new AuthResource(ResourceType.EXCHANGE.toString(), "exchange1", true, "developer", actionsUserGroupsMap); authResourceDao.update(exchange); List<AuthResource> manager = authResourceDao.readAll(ResourceType.EXCHANGE.toString(), "manager"); List<AuthResource> developer = authResourceDao.readAll(ResourceType.EXCHANGE.toString(), "developer"); Assert.assertEquals(manager.size(), 1); Assert.assertEquals(developer.size(), 1); AuthResource exchange1 = authResourceDao.read(ResourceType.EXCHANGE.toString(), "exchange1"); Assert.assertEquals(exchange1.getOwner(), "developer"); List<AuthResource> exchanges = authResourceDao.readAll(ResourceType.EXCHANGE.toString(), "publish", "manager", Collections.singletonList("manager")); Assert.assertEquals(exchanges.size(), 2); }
### Question: AuthResourceInMemoryDao implements AuthResourceDao { @Override public boolean delete(String resourceType, String resource) { AuthResource removedItem = inMemoryResourceMap.remove(resourceType, resource); return removedItem != null; } @Override void persist(AuthResource authResource); @Override void update(AuthResource authResource); @Override boolean delete(String resourceType, String resource); @Override AuthResource read(String resourceType, String resource); @Override List<AuthResource> readAll(String resourceType, String ownerId); @Override List<AuthResource> readAll(String resourceType, String action, String ownerId, List<String> userGroups); @Override boolean isExists(String resourceType, String resourceName); @Override boolean updateOwner(String resourceType, String resourceName, String newOwner); @Override boolean addGroups(String resourceType, String resourceName, String action, List<String> groups); @Override boolean removeGroup(String resourceType, String resourceName, String action, String group); }### Answer: @Test(priority = 3) public void testDelete() throws AuthServerException { authResourceDao.delete(ResourceType.EXCHANGE.toString(), "exchange1"); authResourceDao.delete(ResourceType.EXCHANGE.toString(), "exchange1"); List<AuthResource> manager = authResourceDao.readAll(ResourceType.EXCHANGE.toString(), "manager"); List<AuthResource> developer = authResourceDao.readAll(ResourceType.EXCHANGE.toString(), "developer"); Assert.assertEquals(manager.size(), 1); Assert.assertEquals(developer.size(), 0); boolean exchange1 = authResourceDao.isExists(ResourceType.EXCHANGE.toString(), "exchange1"); boolean exchange2 = authResourceDao.isExists(ResourceType.EXCHANGE.toString(), "exchange2"); Assert.assertEquals(exchange1, false); Assert.assertEquals(exchange2, true); }
### Question: AuthScopeRdbmsDao extends AuthScopeDao { @Override public AuthScope read(String scopeName) throws AuthServerException { Set<String> userGroups = new HashSet<>(); String scopeId = null; Connection connection = null; PreparedStatement statement = null; ResultSet resultSet = null; try { connection = getConnection(); statement = connection.prepareStatement(RdbmsConstants.PS_SELECT_AUTH_SCOPE); statement.setString(1, scopeName); resultSet = statement.executeQuery(); while (resultSet.next()) { if (Objects.isNull(scopeId)) { scopeId = resultSet.getString(1); } String userGroup = resultSet.getString(2); if (Objects.nonNull(userGroup)) { userGroups.add(userGroup); } } } catch (SQLException e) { throw new AuthServerException("Error occurred while retrieving scope for name : " + scopeName, e); } finally { close(connection, statement, resultSet); } if (Objects.nonNull(scopeId)) { return new AuthScope(scopeName, userGroups); } return null; } AuthScopeRdbmsDao(DataSource dataSource); @Override AuthScope read(String scopeName); @Override List<AuthScope> readAll(); @Override void update(String scopeName, List<String> userGroups); }### Answer: @Test public void testRead() throws AuthServerException { AuthScope authScope = authScopeDao.read("exchanges:test"); Assert.assertEquals(authScope.getScopeName(), "exchanges:test"); Assert.assertEquals(authScope.getUserGroups().size(), 1); }
### Question: AuthScopeRdbmsDao extends AuthScopeDao { @Override public List<AuthScope> readAll() throws AuthServerException { Map<String, AuthScope> authScopes = new HashMap<>(); Connection connection = null; PreparedStatement statement = null; ResultSet resultSet = null; try { connection = getConnection(); statement = connection.prepareStatement(RdbmsConstants.PS_SELECT_ALL_AUTH_SCOPES); resultSet = statement.executeQuery(); while (resultSet.next()) { String scopeName = resultSet.getString(1); AuthScope authScope = authScopes.get(scopeName); if (Objects.isNull(authScope)) { authScope = new AuthScope(scopeName, new HashSet<>()); authScopes.put(scopeName, authScope); } if (Objects.nonNull(resultSet.getString(2))) { authScope.addUserGroup(resultSet.getString(2)); } } } catch (SQLException e) { throw new AuthServerException("Error occurred while retrieving scopes", e); } finally { close(connection, statement, resultSet); } return new ArrayList<>(authScopes.values()); } AuthScopeRdbmsDao(DataSource dataSource); @Override AuthScope read(String scopeName); @Override List<AuthScope> readAll(); @Override void update(String scopeName, List<String> userGroups); }### Answer: @Test public void testReadAll() throws AuthServerException { List<AuthScope> authScopes = authScopeDao.readAll(); Assert.assertEquals(authScopes.size(), 19); }
### Question: AuthScopeRdbmsDao extends AuthScopeDao { @Override public void update(String scopeName, List<String> userGroups) throws AuthServerException { Connection connection = null; try { connection = getConnection(); deleteGroups(scopeName, connection); persistGroups(scopeName, userGroups, connection); connection.commit(); } catch (SQLException e) { throw new AuthServerException("Error occurred while updating groups for scope name : " + scopeName, e); } finally { close(connection); } } AuthScopeRdbmsDao(DataSource dataSource); @Override AuthScope read(String scopeName); @Override List<AuthScope> readAll(); @Override void update(String scopeName, List<String> userGroups); }### Answer: @Test public void testUpdate() throws AuthServerException { AuthScope authScope = authScopeDao.read("queues:test"); Assert.assertEquals(authScope.getScopeName(), "queues:test"); Assert.assertEquals(authScope.getUserGroups().size(), 1); authScopeDao.update("queues:test", Arrays.asList("developer", "manager")); authScope = authScopeDao.read("queues:test"); Assert.assertEquals(authScope.getScopeName(), "queues:test"); Assert.assertEquals(authScope.getUserGroups().size(), 2); }
### Question: AmqpConnectionHandler extends ChannelInboundHandlerAdapter { public int closeConnection(String reason, boolean force, boolean used) throws ValidationException { int numberOfChannels = channels.size(); if (!used && numberOfChannels > 0) { throw new ValidationException("Cannot close connection. " + numberOfChannels + " active channels exist " + "and used parameter is not set."); } if (force) { forceCloseConnection(reason); } else { closeConnection(reason); } return numberOfChannels; } AmqpConnectionHandler(AmqpMetricManager metricManager, AmqpChannelFactory amqpChannelFactory, AmqpConnectionManager amqpConnectionManager); void channelRegistered(ChannelHandlerContext ctx); @Override void channelRead(ChannelHandlerContext ctx, Object msg); @Override void channelReadComplete(ChannelHandlerContext ctx); @Override void channelWritabilityChanged(ChannelHandlerContext ctx); @Override void exceptionCaught(ChannelHandlerContext ctx, Throwable cause); void createChannel(int channelId); AmqpChannel getChannel(int channelId); void closeChannel(int channelId); void closeAllChannels(); Broker getBroker(); void attachBroker(Broker broker); boolean isWritable(); String getRemoteAddress(); int getChannelCount(); long getConnectedTime(); int getId(); int closeConnection(String reason, boolean force, boolean used); void closeChannel(int channelId, boolean used, String reason); Collection<AmqpChannelView> getChannelViews(); }### Answer: @Test public void testCloseConnection() throws Exception { int channelCount = 5; for (int i = 1; i <= channelCount; i++) { connectionHandler.createChannel(i); } try { connectionHandler.closeConnection("something", false, false); Assert.fail("Expected ValidationException not thrown"); } catch (ValidationException e) { Assert.assertEquals(e.getMessage(), "Cannot close connection. " + channelCount + " active channels exist and used " + "parameter is not set."); } }
### Question: AmqpConnectionHandler extends ChannelInboundHandlerAdapter { public void closeChannel(int channelId) { AmqpChannel channel = channels.remove(channelId); if (Objects.nonNull(channel)) { closeChannel(channel); } } AmqpConnectionHandler(AmqpMetricManager metricManager, AmqpChannelFactory amqpChannelFactory, AmqpConnectionManager amqpConnectionManager); void channelRegistered(ChannelHandlerContext ctx); @Override void channelRead(ChannelHandlerContext ctx, Object msg); @Override void channelReadComplete(ChannelHandlerContext ctx); @Override void channelWritabilityChanged(ChannelHandlerContext ctx); @Override void exceptionCaught(ChannelHandlerContext ctx, Throwable cause); void createChannel(int channelId); AmqpChannel getChannel(int channelId); void closeChannel(int channelId); void closeAllChannels(); Broker getBroker(); void attachBroker(Broker broker); boolean isWritable(); String getRemoteAddress(); int getChannelCount(); long getConnectedTime(); int getId(); int closeConnection(String reason, boolean force, boolean used); void closeChannel(int channelId, boolean used, String reason); Collection<AmqpChannelView> getChannelViews(); }### Answer: @Test public void testCloseChannel() throws Exception { int channelId = 1; int consumerCount = 5; connectionHandler.createChannel(channelId); Mockito.when(amqpChannel.getConsumerCount()).thenReturn(consumerCount); try { connectionHandler.closeChannel(channelId, false, "something"); Assert.fail("Expected ValidationException not thrown"); } catch (ValidationException e) { Assert.assertEquals(e.getMessage(), "Cannot close channel. " + consumerCount + " active consumers exist and used " + "parameter is not set."); } }
### Question: QueueDelete extends MethodFrame { @Override protected void writeMethod(ByteBuf buf) { buf.writeShort(0); queue.write(buf); int flags = 0x00; if (ifUnused) { flags |= 0x1; } if (ifEmpty) { flags |= 0x2; } if (noWait) { flags |= 0x4; } buf.writeByte(flags); } QueueDelete(int channel, ShortString queue, boolean ifUnused, boolean ifEmpty, boolean noWait); @Override void handle(ChannelHandlerContext ctx, AmqpConnectionHandler connectionHandler); static AmqMethodBodyFactory getFactory(); }### Answer: @Test (dataProvider = "QueueDeleteParams") public void testWriteMethod(String name, boolean ifUnused, boolean ifEmpty, boolean noWait) throws Exception { ShortString queueName = ShortString.parseString(name); QueueDelete frame = new QueueDelete(1, queueName, ifUnused, ifEmpty, noWait); long expectedSize = 2L + queueName.getSize() + 1L; Assert.assertEquals(frame.getMethodBodySize(), expectedSize, "Expected frame size mismatch"); ByteBuf buffer = Unpooled.buffer((int) expectedSize); frame.writeMethod(buffer); buffer.skipBytes(2); Assert.assertEquals(ShortString.parse(buffer), queueName); short flags = buffer.readByte(); Assert.assertEquals(ifUnused, (flags & 0x1) == 0x1); Assert.assertEquals(ifEmpty, (flags & 0x2) == 0x2); Assert.assertEquals(noWait, (flags & 0x4) == 0x4); }
### Question: DbEventMatcher implements EventHandler<DbOperation> { @Override public void onEvent(DbOperation event, long sequence, boolean endOfBatch) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("{} event with message id {} for sequence {}", event.getType(), event.getMessage(), sequence); } eventQueue.add(event.getMessageId()); switch (event.getType()) { case INSERT_MESSAGE: insertMap.put(event.getMessage().getInternalId(), event); break; case DELETE_MESSAGE: long internalId = event.getMessageId(); removeMatchingInsertEvent(event, sequence, internalId); removeMatchingDetachEvents(internalId); break; case DETACH_MSG_FROM_QUEUE: detachMap.computeIfAbsent(event.getMessageId(), k -> new ArrayList<>()) .add(event); break; case READ_MSG_DATA: case NO_OP: break; default: if (LOGGER.isDebugEnabled()) { LOGGER.error("Unknown event type " + event.getType()); } } removeOldestEntryFromIndex(); event.completeProcessing(); } DbEventMatcher(int ringBufferSize); @Override void onEvent(DbOperation event, long sequence, boolean endOfBatch); }### Answer: @Test(dataProvider = "testDbOperationData") public void testInsertsCancelOut(TestOperationRequest[] testOperationsArray) { for (int i = 0; i < testOperationsArray.length; i++) { operationsList.add(DbOperation.getFactory().newInstance()); TestOperationRequest request = testOperationsArray[i]; if (request.beforeType == INSERT_MESSAGE) { operationsList.get(i).insertMessage(new Message(request.messageId, new Metadata("queue1", "amq.direct", 0))); } else if (request.beforeType == DELETE_MESSAGE) { operationsList.get(i).deleteMessage(request.messageId); } else { operationsList.get(i).detachFromQueue("queue1", request.messageId); } } for (int i = 0; i < testOperationsArray.length; i++) { dbEventMatcher.onEvent(operationsList.get(i), i, false); } for (int i = 0; i < testOperationsArray.length; i++) { Assert.assertTrue(operationsList.get(i).acquireForPersisting(), "Must be able to acquire for persisting."); Assert.assertEquals(operationsList.get(i).getType(), testOperationsArray[i].afterType, "Operation type after operation doesn't match for operation " + (i + 1) + "."); } }
### Question: AmqMethodRegistry { public AmqMethodBodyFactory getFactory(short classId, short methodId) throws AmqFrameDecodingException { try { AmqMethodBodyFactory factory = factories[classId][methodId]; if (factory == null) { throw new AmqFrameDecodingException(AmqConstant.COMMAND_INVALID, "Method " + methodId + " unknown in AMQP version 0-91" + " (while trying to decode class " + classId + " method " + methodId + "."); } return factory; } catch (NullPointerException e) { throw new AmqFrameDecodingException(AmqConstant.COMMAND_INVALID, "Class " + classId + " unknown in AMQP version 0-91" + " (while trying to decode class " + classId + " method " + methodId + "."); } catch (IndexOutOfBoundsException e) { if (classId >= factories.length) { throw new AmqFrameDecodingException(AmqConstant.COMMAND_INVALID, "Class " + classId + " unknown in AMQP version 0-91" + " (while trying to decode class " + classId + " method " + methodId + "."); } else { throw new AmqFrameDecodingException(AmqConstant.COMMAND_INVALID, "Method " + methodId + " unknown in AMQP version 0-91" + " (while trying to decode class " + classId + " method " + methodId + "."); } } } AmqMethodRegistry(AuthenticationStrategy authenticationStrategy); AmqMethodBodyFactory getFactory(short classId, short methodId); public AmqMethodBodyFactory[][] factories; }### Answer: @Test(expectedExceptions = AmqFrameDecodingException.class) public void testInvalidMethodValue() throws Exception { AmqMethodBodyFactory factory = new AmqMethodRegistry(authenticationStrategy).getFactory((short) 12, (short) 12); } @Test(expectedExceptions = AmqFrameDecodingException.class) public void testLargeMethodValue() throws Exception { AmqMethodBodyFactory factory = new AmqMethodRegistry(authenticationStrategy).getFactory((short) 10, (short) 2000); } @Test(expectedExceptions = AmqFrameDecodingException.class) public void testLargeClassValue() throws Exception { AmqMethodBodyFactory factory = new AmqMethodRegistry(authenticationStrategy).getFactory((short) 2000, (short) 10); } @Test(expectedExceptions = AmqFrameDecodingException.class) public void testInvalidMethodValueInValidClass() throws Exception { AmqMethodBodyFactory factory = new AmqMethodRegistry(authenticationStrategy).getFactory((short) 60, (short) 5); }
### Question: AmqpChannel implements AmqpChannelView { @Override public String getTransactionType() { String transactionType = "unidentified"; if (transaction instanceof AutoCommitTransaction) { transactionType = "AutoCommit"; } else if (transaction instanceof LocalTransaction) { transactionType = "LocalTransaction"; } else if (transaction instanceof DistributedTransaction) { transactionType = "DistributedTransaction"; } return transactionType; } AmqpChannel(AmqpServerConfiguration configuration, Broker broker, int channelId, AmqpMetricManager metricManager, AmqpConnectionHandler connection); void declareExchange(String exchangeName, String exchangeType, boolean passive, boolean durable); void deleteExchange(String exchangeName, boolean ifUnused); void declareQueue(ShortString queue, boolean passive, boolean durable, boolean autoDelete); void bind(ShortString queue, ShortString exchange, ShortString routingKey, FieldTable arguments); void unbind(ShortString queue, ShortString exchange, ShortString routingKey); AmqpConsumer consume(ShortString queueName, ShortString consumerTag, boolean exclusive, ChannelHandlerContext ctx); void close(); void cancelConsumer(ShortString consumerTag); InMemoryMessageAggregator getMessageAggregator(); void acknowledge(long deliveryTag, boolean multiple); int getNextConsumerTag(); long getNextDeliveryTag(); @Override int getChannelId(); @Override int getConsumerCount(); @Override int getUnackedMessageCount(); @Override int getDeliveryPendingMessageCount(); @Override String getTransactionType(); @Override int getPrefetchCount(); @Override long getCreatedTime(); void recordMessageDelivery(long deliveryTag, AckData ackData); void reject(long deliveryTag, boolean requeue); Collection<AckData> recover(); void requeueAll(); int getConnectionId(); void setFlow(boolean active); boolean isReady(); @Override boolean isClosed(); @Override boolean isFlowEnabled(); ChannelFlowManager getFlowManager(); void hold(AmqpDeliverMessage deliverMessage); List<AmqpDeliverMessage> getPendingMessages(); void setPrefetchCount(int prefetchCount); AmqpDeliverMessage createDeliverMessage(Message message, ShortString consumerTag, String queueName); void setLocalTransactional(); void setDistributedTransactional(); void commit(); void rollback(); boolean isNonTransactional(); void startDtx(Xid xid, boolean join, boolean resume); void endDtx(Xid xid, boolean fail, boolean suspend); void prepare(Xid xid); void commit(Xid xid, boolean onePhase); void rollback(Xid xid); void forget(Xid xid); void setTimeout(Xid xid, long timeout); static final String DELIVERY_TAG_FIELD_NAME; static final String CHANNEL_ID_FIELD_NAME; }### Answer: @Test public void testGetTransactionType() throws Exception { Assert.assertEquals(amqpChannel.getTransactionType(), "AutoCommit"); amqpChannel.setLocalTransactional(); Assert.assertEquals(amqpChannel.getTransactionType(), "LocalTransaction"); amqpChannel.setDistributedTransactional(); Assert.assertEquals(amqpChannel.getTransactionType(), "DistributedTransaction"); }
### Question: ChannelFlowManager { public void notifyMessageAddition(ChannelHandlerContext ctx) { messagesInFlight++; if (messagesInFlight > highLimit && inflowEnabled) { inflowEnabled = false; ctx.writeAndFlush(new ChannelFlow(channel.getChannelId(), false)); ctx.channel().config().setAutoRead(false); LOGGER.info("Inflow disabled for channel {}-{}", channel.getChannelId(), ctx.channel().remoteAddress()); } } ChannelFlowManager(AmqpChannel channel, int lowLimit, int highLimit); void notifyMessageAddition(ChannelHandlerContext ctx); void notifyMessageRemoval(ChannelHandlerContext ctx); }### Answer: @Test public void testFlowNotDisabledWhenHighLevelNotExceeded() throws Exception { IntStream.rangeClosed(1, 10) .forEach(i -> channelFlowManager.notifyMessageAddition(ctx)); Mockito.verify(ctx, Mockito.never()).writeAndFlush(argumentCaptor.capture()); } @Test public void testFlowDisabledWhenHighLevelExceeded() throws Exception { IntStream.rangeClosed(1, 11) .forEach(i -> channelFlowManager.notifyMessageAddition(ctx)); Mockito.verify(ctx, Mockito.times(1)).writeAndFlush(argumentCaptor.capture()); }
### Question: AmqpConsumer extends Consumer { public Properties getTransportProperties() { return transportProperties; } AmqpConsumer(ChannelHandlerContext ctx, Broker broker, AmqpChannel channel, String queueName, ShortString consumerTag, boolean isExclusive); @Override void send(Message message); @Override String getQueueName(); @Override void close(); @Override boolean isExclusive(); void enableConsume(); ShortString getConsumerTag(); @Override boolean isReady(); @Override String toString(); Properties getTransportProperties(); static final String CONSUMER_TAG_FIELD_NAME; }### Answer: @Test public void testGetTransportProperties() throws Exception { AmqpChannel amqpChannel = Mockito.mock(AmqpChannel.class); ChannelHandlerContext context = Mockito.mock(ChannelHandlerContext.class); Broker broker = Mockito.mock(Broker.class); Mockito.when(amqpChannel.getChannelId()).thenReturn(5); Mockito.when(amqpChannel.getConnectionId()).thenReturn(7); AmqpConsumer consumer = new AmqpConsumer(context, broker, amqpChannel, "queue", new ShortString(0, new byte[0]), true); Properties transportProperties = consumer.getTransportProperties(); Assert.assertEquals(transportProperties.get(AmqConstant.TRANSPORT_PROPERTY_CHANNEL_ID), 5, "Incorrect channel id set"); Assert.assertEquals(transportProperties.get(AmqConstant.TRANSPORT_PROPERTY_CONNECTION_ID), 7, "Incorrect connection id set"); }
### Question: ChunkConverter { public List<ContentChunk> convert(List<ContentChunk> chunkList, long totalLength) { if (chunkList.isEmpty() || isChunksUnderLimit(chunkList)) { return chunkList; } ArrayList<ContentChunk> convertedChunks = new ArrayList<>(); long pendingBytes = totalLength; long offset = 0; ContentReader contentReader = new ContentReader(chunkList); while (pendingBytes > 0) { long newBufferLength = Math.min(pendingBytes, maxChunkSizeLimit); ContentChunk newChunk = new ContentChunk(offset, contentReader.getNextBytes((int) newBufferLength)); convertedChunks.add(newChunk); pendingBytes = pendingBytes - newBufferLength; offset = offset + newBufferLength; } return convertedChunks; } ChunkConverter(int maxChunkSizeLimit); List<ContentChunk> convert(List<ContentChunk> chunkList, long totalLength); }### Answer: @Test public void testConvertLarge() { ChunkConverter converter = new ChunkConverter(10); int chunkLength = 12; String stringData = RandomStringGenerator.randomString(chunkLength); List<ContentChunk> beforeList = createContentChunks(stringData, 1); List<ContentChunk> afterList = converter.convert(beforeList, chunkLength); Assert.assertEquals(afterList.size(), 2, "After converting there should be only two chunks"); String convertedDataString = getString(afterList, chunkLength); Assert.assertEquals(convertedDataString, stringData, "Content should be equal after conversion"); } @Test public void testConvertLargeMultiple() { ChunkConverter converter = new ChunkConverter(10); int chunkLength = 30; String stringData = RandomStringGenerator.randomString(chunkLength); List<ContentChunk> beforeList = createContentChunks(stringData, 2); List<ContentChunk> afterList = converter.convert(beforeList, chunkLength); Assert.assertEquals(afterList.size(), 3, "After converting there should be only three chunks"); String convertedDataString = getString(afterList, chunkLength); Assert.assertEquals(convertedDataString, stringData, "Content should be equal after conversion"); } @Test public void testConvertSmall() { ChunkConverter converter = new ChunkConverter(10); int chunkLength = 8; List<ContentChunk> beforeList = createContentChunk(chunkLength); List<ContentChunk> afterList = converter.convert(beforeList, chunkLength); Assert.assertEquals(afterList, beforeList, "Smaller chunks should not be converted"); } @Test public void testConvertEmpty() { ChunkConverter converter = new ChunkConverter(10); int chunkLength = 8; List<ContentChunk> beforeList = new ArrayList<>(); List<ContentChunk> afterList = converter.convert(beforeList, chunkLength); Assert.assertEquals(afterList, beforeList, "Empty chunk list should not be converted"); }
### Question: BindingsRegistry { void bind(QueueHandler queueHandler, String bindingKey, FieldTable arguments) throws BrokerException, ValidationException { BindingSet bindingSet = bindingPatternToBindingsMap.computeIfAbsent(bindingKey, k -> new BindingSet()); Queue queue = queueHandler.getUnmodifiableQueue(); Binding binding = new Binding(queue, bindingKey, arguments); boolean success = bindingSet.add(binding); if (success) { queueHandler.addBinding(binding, bindingDeleteListener); if (queue.isDurable()) { bindingDao.persist(exchange.getName(), binding); } } LOGGER.debug("Binding added for queue {} with pattern {}", queueHandler, bindingKey); notifyOnBind(bindingKey); } BindingsRegistry(Exchange exchange, BindingDao bindingDao); void retrieveAllBindingsForExchange(QueueRegistry queueRegistry); Map<String, BindingSet> getAllBindings(); void addBindingsRegistryListeners(BindingsRegistryListener listener); }### Answer: @Test(dataProvider = "InvalidBindingData", expectedExceptions = ValidationException.class) public void testMultipleBindCallsWithDifferentSelectors(String queueName, String selectorOne, String selectorTwo) throws Exception { QueueHandler queueHandler = new QueueHandler(new MemQueueImpl(queueName, 2, false), null); registry.bind(queueHandler, queueName, getFieldTable(selectorOne)); registry.bind(queueHandler, queueName, getFieldTable(selectorTwo)); }
### Question: TopicExchange extends Exchange implements BindingsRegistryListener { @Override public BindingSet getBindingsForRoute(String routingKey) { if (routingKey.isEmpty()) { return BindingSet.emptySet(); } lock.readLock().lock(); try { BindingSet matchedBindingSet = new BindingSet(); fastTopicMatcher.matchingBindings(routingKey, subscribedPattern -> { BindingSet bindingSet = getBindingsRegistry().getBindingsForRoute(subscribedPattern); matchedBindingSet.add(bindingSet); }); return matchedBindingSet; } finally { lock.readLock().unlock(); } } TopicExchange(String exchangeName, BindingDao bindingDao); @Override BindingSet getBindingsForRoute(String routingKey); @Override void onBind(String routingKey); @Override void onUnbind(String routingKey, boolean isLastSubscriber); @Override void onRetrieveAllBindingsForExchange(String routingKey); }### Answer: @Test(dataProvider = "positiveTopicPairs", description = "Test positive topic matching") public void testPositiveSingleTopicMatching(String subscribedPattern, String publishedTopic) throws BrokerException, ValidationException { DbBackedQueueHandlerFactory factory = new DbBackedQueueHandlerFactory(null, new NullBrokerMetricManager(), new BrokerCoreConfiguration()); QueueHandler handler = factory.createNonDurableQueueHandler(subscribedPattern, false); topicExchange.bind(handler, subscribedPattern, FieldTable.EMPTY_TABLE); BindingSet bindingSet = topicExchange.getBindingsForRoute(publishedTopic); Collection<Binding> unfilteredBindings = bindingSet.getUnfilteredBindings(); Assert.assertEquals(unfilteredBindings.iterator().hasNext(), true, "No matches found."); Assert.assertEquals( unfilteredBindings.iterator().next().getQueue().getName(), subscribedPattern, "No matches found."); } @Test(dataProvider = "negativeTopicPairs", description = "Test negative topic matching") public void testNegativeSingleTopicMatching(String subscribedPattern, String publishedTopic) throws BrokerException, ValidationException { DbBackedQueueHandlerFactory factory = new DbBackedQueueHandlerFactory(null, new NullBrokerMetricManager(), new BrokerCoreConfiguration()); QueueHandler handler = factory.createNonDurableQueueHandler(subscribedPattern, false); topicExchange.bind(handler, subscribedPattern, FieldTable.EMPTY_TABLE); BindingSet bindingSet = topicExchange.getBindingsForRoute(publishedTopic); Collection<Binding> unfilteredBindings = bindingSet.getUnfilteredBindings(); Assert.assertEquals(unfilteredBindings.iterator().hasNext(), false, "No topic should match"); } @Test(dataProvider = "positiveTopicPairs", description = "Test topic removal") public void testTopicRemoval(String subscribedPattern, String publishedTopic) throws BrokerException, ValidationException { DbBackedQueueHandlerFactory factory = new DbBackedQueueHandlerFactory(null, new NullBrokerMetricManager(), new BrokerCoreConfiguration()); QueueHandler handler = factory.createNonDurableQueueHandler(subscribedPattern, false); Queue queue = handler.getUnmodifiableQueue(); topicExchange.bind(handler, subscribedPattern, FieldTable.EMPTY_TABLE); topicExchange.unbind(queue, subscribedPattern); BindingSet bindingSet = topicExchange.getBindingsForRoute(publishedTopic); Collection<Binding> unfilteredBindings = bindingSet.getUnfilteredBindings(); Assert.assertEquals(unfilteredBindings.iterator().hasNext(), false, "No topic should match"); }
### Question: CipherToolInitializer { public static void execute(String... toolArgs) { CommandLineParser commandLineParser; try { commandLineParser = Utils.createCommandLineParser(toolArgs); } catch (CipherToolException e) { printHelpMessage(); throw new CipherToolRuntimeException("Unable to run CipherTool", e); } URLClassLoader urlClassLoader = Utils.getCustomClassLoader(commandLineParser.getCustomLibPath()); String brokerFilePath = System.getProperty(CipherToolConstants.SYSTEM_PARAM_BROKER_CONFIG_FILE); String configYamlPath = commandLineParser.getCustomConfigPath().orElse(brokerFilePath); String commandName = commandLineParser.getCommandName().orElse(""); String commandParam = commandLineParser.getCommandParam().orElse(""); try { Path secureVaultConfigPath = Paths.get(configYamlPath); Object objCipherTool = Utils.createCipherTool(urlClassLoader, secureVaultConfigPath); processCommand(commandName, commandParam, objCipherTool); if (LOGGER.isDebugEnabled()) { if (commandLineParser.getCommandName().isPresent()) { LOGGER.debug("Command: " + commandName + " executed successfully with configuration file " + "path: " + secureVaultConfigPath.toString()); } else { LOGGER.debug("Secrets encrypted successfully with configuration file path: " + secureVaultConfigPath.toString()); } } } catch (CipherToolException e) { throw new CipherToolRuntimeException("Unable to run CipherTool", e); } } static void main(String[] args); static void execute(String... toolArgs); }### Answer: @Test(expectedExceptions = {CipherToolRuntimeException.class}) public void testExecuteTestEncryptSecretsWithOddParameters() { String[] toolArgs = new String[]{"-customLibPath", "/tmp", "xyz"}; CipherToolInitializer.execute(toolArgs); } @Test(expectedExceptions = {CipherToolRuntimeException.class}) public void testExecuteTestEncryptSecretsWithWrongCommand() { String[] toolArgs = new String[]{"-ENCRYPTTEXT", "Ballerina@WSO2"}; CipherToolInitializer.execute(toolArgs); } @Test public void testExecuteTestEncryptText() { String[] toolArgs = new String[]{"-encryptText", "Ballerina@WSO2", "-configPath", secureVaultYAMLPath.toString()}; CipherToolInitializer.execute(toolArgs); } @Test public void testExecuteTestDecryptText() { String[] toolArgs = new String[]{"-decryptText", "lDaF2UWOEK7NNS3Sbu1jk4OJtGjTD88LWHTUNBiAAEnW/mWGyOZ4wu8xL4B5oVZH1n7oFTac6YBl8Q96VJMfZo0PJ8fAm0ALIEhd" + "qXMOe6e2sUISnrPOf4xqdrRN+N1arEgzmNOZ+51OjznyIL3hiCJ9boYeJX1DufIDpqL0Q/M0g5Tglu4w15bhzCgwzI" + "yL7u3qs5eDwsL+GfV5kRtk9giBU5dkvWxxVfdRzHj7OxpN4JpodN+dcY0fhtgHUS/s0f03fp9ZQqB7pKTl2SYIRjhc" + "SaQxV3Moih7RCLsYdoLiIZRG3uZJUzHEAU2Z/Sd0R8enPIQ64qoWEm3GhCsuxQ==", "-configPath", secureVaultYAMLPath.toString()}; CipherToolInitializer.execute(toolArgs); }
### Question: QueueBuffer { public int size() { return size.get(); } QueueBuffer(int inMemoryLimit, int indelibleMessageLimit, MessageReader messageReader); synchronized void add(Message message); synchronized void addAllBareMessages(Collection<Message> messages); synchronized void addBareMessage(Message message); synchronized boolean addIndelibleMessage(Message message); synchronized void remove(long messageId); synchronized void removeAll(Collection<DetachableMessage> messages); int size(); int getNumberOfInflightMessages(); int getNumberOfUndeliveredMessages(); synchronized Message getFirstDeliverable(); void markMessageFilled(Message message); void markMessageFillFailed(Message message); synchronized int clear(Consumer<Message> postDeleteAction); }### Answer: @Test public void testSize() { QueueBuffer queueBuffer = new QueueBuffer(10, 0, messageReader); for (int i = 0; i < 12; i++) { Message message = new Message(i + 1, mockMetadata); queueBuffer.add(message); } Assert.assertEquals(queueBuffer.size(), 12, "Message size should match the number of added items"); }
### Question: CarbonConfigAdapter implements ConfigProvider { @Override public <T> T getConfigurationObject(Class<T> aClass) throws ConfigurationException { return getConfig(aClass.getCanonicalName(), aClass); } CarbonConfigAdapter(BrokerConfigProvider configProvider); @Override T getConfigurationObject(Class<T> aClass); @Override Object getConfigurationObject(String s); @Override T getConfigurationObject(String s, Class<T> aClass); }### Answer: @Test public void testGetConfigurationObject() throws Exception { CarbonConfigAdapter carbonConfigAdapter = new CarbonConfigAdapter(configProvider); TestConfig configurationObject = (TestConfig) carbonConfigAdapter.getConfigurationObject(TEST_CONFIG_NAMESPACE); Assert.assertEquals(configurationObject.getTestField(), NAMESPACE_KEY); } @Test public void testGetConfigurationObject1() throws Exception { CarbonConfigAdapter carbonConfigAdapter = new CarbonConfigAdapter(configProvider); TestConfig configurationObject = carbonConfigAdapter.getConfigurationObject(TestConfig.class); Assert.assertEquals(configurationObject.getTestField(), CLASS_KEY); } @Test public void testGetConfigurationObject2() throws Exception { CarbonConfigAdapter carbonConfigAdapter = new CarbonConfigAdapter(configProvider); TestConfig configurationObject = carbonConfigAdapter.getConfigurationObject(TEST_CONFIG_NAMESPACE, TestConfig.class); Assert.assertEquals(configurationObject.getTestField(), NAMESPACE_KEY); } @Test(expectedExceptions = ConfigurationException.class) public void testGetInvalidConfigurationObject() throws Exception { CarbonConfigAdapter carbonConfigAdapter = new CarbonConfigAdapter(configProvider); TestConfig configurationObject = carbonConfigAdapter.getConfigurationObject("invalid.namespace", TestConfig.class); Assert.assertEquals(configurationObject.getTestField(), NAMESPACE_KEY); }
### Question: LongString implements EncodableData { @Override public long getSize() { return 4 + length; } @SuppressFBWarnings("EI_EXPOSE_REP2") LongString(long length, byte[] content); static LongString parseString(String data); @Override long getSize(); @Override void write(ByteBuf buf); static LongString parse(ByteBuf buf); static LongString parse(byte[] data); @Override boolean equals(Object obj); boolean isEmpty(); @Override int hashCode(); @Override String toString(); @SuppressFBWarnings("EI_EXPOSE_REP") byte[] getBytes(); }### Answer: @Test public void testGetSize() throws Exception { Assert.assertEquals(DEFAULT_TEST_OBJECT.getSize(), DEFAULT_DATA_STRING.length() + 4, "getSize should return " + "required byte array size"); }
### Question: LongString implements EncodableData { public static LongString parse(ByteBuf buf) throws Exception { int size = (int) buf.readUnsignedInt(); if (size < 0) { throw new Exception("Invalid string length"); } byte[] data = new byte[size]; buf.readBytes(data); return new LongString(size, data); } @SuppressFBWarnings("EI_EXPOSE_REP2") LongString(long length, byte[] content); static LongString parseString(String data); @Override long getSize(); @Override void write(ByteBuf buf); static LongString parse(ByteBuf buf); static LongString parse(byte[] data); @Override boolean equals(Object obj); boolean isEmpty(); @Override int hashCode(); @Override String toString(); @SuppressFBWarnings("EI_EXPOSE_REP") byte[] getBytes(); }### Answer: @Test public void testParse() throws Exception { ByteBuf buf = Unpooled.buffer(DEFAULT_DATA_STRING.length() + 4); DEFAULT_TEST_OBJECT.write(buf); LongString parsedObject = LongString.parse(buf); Assert.assertEquals(parsedObject, DEFAULT_TEST_OBJECT, "Encoding and decoding should match to same object"); } @Test(expectedExceptions = Exception.class) public void testInvalidBuffer() throws Exception { ByteBuf buf = Unpooled.buffer(DEFAULT_DATA_STRING.length() + 4); buf.writeLong(-2); LongString.parse(buf); }
### Question: LongString implements EncodableData { @Override public String toString() { return new String(content, StandardCharsets.UTF_8); } @SuppressFBWarnings("EI_EXPOSE_REP2") LongString(long length, byte[] content); static LongString parseString(String data); @Override long getSize(); @Override void write(ByteBuf buf); static LongString parse(ByteBuf buf); static LongString parse(byte[] data); @Override boolean equals(Object obj); boolean isEmpty(); @Override int hashCode(); @Override String toString(); @SuppressFBWarnings("EI_EXPOSE_REP") byte[] getBytes(); }### Answer: @Test public void testToString() throws Exception { Assert.assertEquals(DEFAULT_TEST_OBJECT.toString(), DEFAULT_DATA_STRING, "toString() should match the data " + "string used to create it"); }
### Question: QueueBuffer { public synchronized Message getFirstDeliverable() { submitMessageReads(); Node deliverableCandidate = firstDeliverableCandidate; if (deliverableCandidate != firstUndeliverable) { if (!deliverableCandidate.hasContent()) { return null; } firstDeliverableCandidate = deliverableCandidate.next; recordRemovingMessageForDelivery(); return deliverableCandidate.item; } else if (firstUndeliverable != null && firstUndeliverable.hasContent()) { Node newDeliverable = firstUndeliverable; firstDeliverableCandidate = firstUndeliverable.next; pushFirstUndeliverableCursor(); recordRemovingMessageForDelivery(); return newDeliverable.item; } else { return null; } } QueueBuffer(int inMemoryLimit, int indelibleMessageLimit, MessageReader messageReader); synchronized void add(Message message); synchronized void addAllBareMessages(Collection<Message> messages); synchronized void addBareMessage(Message message); synchronized boolean addIndelibleMessage(Message message); synchronized void remove(long messageId); synchronized void removeAll(Collection<DetachableMessage> messages); int size(); int getNumberOfInflightMessages(); int getNumberOfUndeliveredMessages(); synchronized Message getFirstDeliverable(); void markMessageFilled(Message message); void markMessageFillFailed(Message message); synchronized int clear(Consumer<Message> postDeleteAction); }### Answer: @Test public void testGetFirstDeliverable() { QueueBuffer queueBuffer = new QueueBuffer(10, 0, messageReader); for (int i = 0; i < 12; i++) { Message message = new Message(i + 1, mockMetadata); queueBuffer.add(message); } for (int i = 0; i < 12; i++) { Message message = queueBuffer.getFirstDeliverable(); Assert.assertNotNull(message.getMetadata(), "Messages returned from #getFirstDeliverable() should never " + "be empty"); queueBuffer.remove(message.getInternalId()); } Assert.assertEquals(queueBuffer.size(), 0, "Buffer size should be 0 after removing all messages"); }
### Question: LongString implements EncodableData { @Override public boolean equals(Object obj) { if (this == obj) { return true; } return (obj instanceof LongString) && (Arrays.equals(content, ((LongString) obj).content)); } @SuppressFBWarnings("EI_EXPOSE_REP2") LongString(long length, byte[] content); static LongString parseString(String data); @Override long getSize(); @Override void write(ByteBuf buf); static LongString parse(ByteBuf buf); static LongString parse(byte[] data); @Override boolean equals(Object obj); boolean isEmpty(); @Override int hashCode(); @Override String toString(); @SuppressFBWarnings("EI_EXPOSE_REP") byte[] getBytes(); }### Answer: @Test public void testEquals() throws Exception { LongString other = LongString.parseString("different string"); LongString similar = LongString.parseString(DEFAULT_DATA_STRING); Assert.assertTrue(DEFAULT_TEST_OBJECT.equals(DEFAULT_TEST_OBJECT), "equals() should return true for similar objects"); Assert.assertTrue(DEFAULT_TEST_OBJECT.equals(similar), "equals() should return true for similar objects"); Assert.assertFalse(DEFAULT_TEST_OBJECT.equals(other), "equals() should return false for different objects"); Assert.assertFalse(DEFAULT_TEST_OBJECT.equals(DEFAULT_DATA_STRING), "equals() should return false for different objects"); }
### Question: LongString implements EncodableData { @Override public int hashCode() { return Arrays.hashCode(content); } @SuppressFBWarnings("EI_EXPOSE_REP2") LongString(long length, byte[] content); static LongString parseString(String data); @Override long getSize(); @Override void write(ByteBuf buf); static LongString parse(ByteBuf buf); static LongString parse(byte[] data); @Override boolean equals(Object obj); boolean isEmpty(); @Override int hashCode(); @Override String toString(); @SuppressFBWarnings("EI_EXPOSE_REP") byte[] getBytes(); }### Answer: @Test public void testHashCode() throws Exception { LongString similar = LongString.parseString(DEFAULT_DATA_STRING); Assert.assertEquals(similar.hashCode(), DEFAULT_TEST_OBJECT.hashCode(), "Hashcode should match for similar " + "data"); }
### Question: LongUint implements EncodableData { @Override public long getSize() { return 4L; } private LongUint(long value); @Override long getSize(); @Override void write(ByteBuf buf); long getInt(); @Override int hashCode(); @Override boolean equals(Object obj); static LongUint parse(ByteBuf buf); static LongUint parse(long value); @Override String toString(); }### Answer: @Test public void testGetSize() { Assert.assertEquals(TEST_OBJECT.getSize(), 4, "Size of long-uint should be 4"); }
### Question: LongUint implements EncodableData { @Override public boolean equals(Object obj) { if (this == obj) { return true; } return (obj instanceof LongUint) && (value == ((LongUint) obj).value); } private LongUint(long value); @Override long getSize(); @Override void write(ByteBuf buf); long getInt(); @Override int hashCode(); @Override boolean equals(Object obj); static LongUint parse(ByteBuf buf); static LongUint parse(long value); @Override String toString(); }### Answer: @Test public void testEquals() { LongUint other = LongUint.parse(3); LongUint similar = LongUint.parse(DATA_VALUE); Assert.assertTrue(TEST_OBJECT.equals(TEST_OBJECT), "equals() should return true for similar objects"); Assert.assertTrue(TEST_OBJECT.equals(similar), "equals() should return true for similar objects"); Assert.assertFalse(TEST_OBJECT.equals(other), "equals() should return false for different objects"); Assert.assertFalse(TEST_OBJECT.equals(DATA_VALUE), "equals() should return false for different objects"); }
### Question: LongUint implements EncodableData { @Override public int hashCode() { return Objects.hash(value); } private LongUint(long value); @Override long getSize(); @Override void write(ByteBuf buf); long getInt(); @Override int hashCode(); @Override boolean equals(Object obj); static LongUint parse(ByteBuf buf); static LongUint parse(long value); @Override String toString(); }### Answer: @Test public void testHashCode() { LongUint similar = LongUint.parse(DATA_VALUE); Assert.assertEquals(similar.hashCode(), TEST_OBJECT.hashCode(), "Hashcode should match for similar data"); }
### Question: LongUint implements EncodableData { public static LongUint parse(ByteBuf buf) { return new LongUint(buf.readUnsignedInt()); } private LongUint(long value); @Override long getSize(); @Override void write(ByteBuf buf); long getInt(); @Override int hashCode(); @Override boolean equals(Object obj); static LongUint parse(ByteBuf buf); static LongUint parse(long value); @Override String toString(); }### Answer: @Test public void testParse() { ByteBuf buf = Unpooled.buffer(4); TEST_OBJECT.write(buf); LongUint parsedObject = LongUint.parse(buf); Assert.assertEquals(parsedObject, TEST_OBJECT, "Encoding and decoding should result in the same object"); }
### Question: ShortShortUint implements EncodableData { @Override public long getSize() { return 1L; } private ShortShortUint(short value); @Override long getSize(); @Override void write(ByteBuf buf); static ShortShortUint parse(ByteBuf buf); static ShortShortUint parse(short value); short getByte(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }### Answer: @Test public void testGetSize() { Assert.assertEquals(TEST_OBJECT.getSize(), 1, "Size of short-short-uint should be 1"); }
### Question: ShortShortUint implements EncodableData { @Override public boolean equals(Object obj) { if (this == obj) { return true; } return (obj instanceof ShortShortUint) && (value == ((ShortShortUint) obj).value); } private ShortShortUint(short value); @Override long getSize(); @Override void write(ByteBuf buf); static ShortShortUint parse(ByteBuf buf); static ShortShortUint parse(short value); short getByte(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }### Answer: @Test public void testEquals() { ShortShortUint other = ShortShortUint.parse((short) 3); ShortShortUint similar = ShortShortUint.parse(DATA_VALUE); Assert.assertTrue(TEST_OBJECT.equals(TEST_OBJECT), "equals() should return true for similar objects"); Assert.assertTrue(TEST_OBJECT.equals(similar), "equals() should return true for similar objects"); Assert.assertFalse(TEST_OBJECT.equals(other), "equals() should return false for different objects"); Assert.assertFalse(TEST_OBJECT.equals(DATA_VALUE), "equals() should return false for different objects"); }
### Question: ShortShortUint implements EncodableData { @Override public int hashCode() { return (int) value; } private ShortShortUint(short value); @Override long getSize(); @Override void write(ByteBuf buf); static ShortShortUint parse(ByteBuf buf); static ShortShortUint parse(short value); short getByte(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }### Answer: @Test public void testHashCode() { ShortShortUint similar = ShortShortUint.parse(DATA_VALUE); Assert.assertEquals(similar.hashCode(), TEST_OBJECT.hashCode(), "Hashcode should match for similar data"); }
### Question: ExchangeRegistry { Exchange getExchange(String exchangeName) { return exchangeMap.get(exchangeName); } ExchangeRegistry(ExchangeDao exchangeDao, BindingDao bindingDao); void createExchange(String exchangeName, Exchange.Type type, boolean durable); Exchange getDefaultExchange(); void retrieveFromStore(QueueRegistry queueRegistry); Collection<Exchange> getAllExchanges(); static final String DEFAULT_DEAD_LETTER_EXCHANGE; }### Answer: @Test(dataProvider = "exchangeNames", description = "test frequently used exchanges types are defined") public void testGetExchanges(String exchangeName) { Exchange exchange = exchangeRegistry.getExchange(exchangeName); Assert.assertNotNull(exchange, "unable to find the exchange"); Assert.assertEquals(exchange.getName(), exchangeName, "invalid exchange returned"); }
### Question: ShortShortUint implements EncodableData { public static ShortShortUint parse(ByteBuf buf) { return new ShortShortUint(buf.readUnsignedByte()); } private ShortShortUint(short value); @Override long getSize(); @Override void write(ByteBuf buf); static ShortShortUint parse(ByteBuf buf); static ShortShortUint parse(short value); short getByte(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }### Answer: @Test public void testParse() { ByteBuf buf = Unpooled.buffer(1); TEST_OBJECT.write(buf); ShortShortUint parsedObject = ShortShortUint.parse(buf); Assert.assertEquals(parsedObject, TEST_OBJECT, "Encoding and decoding should result in the same object"); }
### Question: ShortString implements EncodableData { public long getSize() { return length + 1; } @SuppressFBWarnings("EI_EXPOSE_REP2") ShortString(long length, byte[] content); long getSize(); void write(ByteBuf buf); static ShortString parse(ByteBuf buf); static ShortString parseString(String data); @Override String toString(); @Override boolean equals(Object obj); @Override int hashCode(); boolean isEmpty(); }### Answer: @Test public void testGetSize() throws Exception { Assert.assertEquals(DEFAULT_TEST_OBJECT.getSize(), DEFAULT_DATA_STRING.length() + 1, "getSize should return " + "required byte array size"); }
### Question: ShortString implements EncodableData { public static ShortString parse(ByteBuf buf) { int size = buf.readUnsignedByte(); byte[] data = new byte[size]; buf.readBytes(data); return new ShortString(size, data); } @SuppressFBWarnings("EI_EXPOSE_REP2") ShortString(long length, byte[] content); long getSize(); void write(ByteBuf buf); static ShortString parse(ByteBuf buf); static ShortString parseString(String data); @Override String toString(); @Override boolean equals(Object obj); @Override int hashCode(); boolean isEmpty(); }### Answer: @Test public void testParse() throws Exception { ByteBuf buf = Unpooled.buffer(DEFAULT_DATA_STRING.length() + 1); DEFAULT_TEST_OBJECT.write(buf); ShortString parsedObject = ShortString.parse(buf); Assert.assertEquals(parsedObject, DEFAULT_TEST_OBJECT, "Encoding and decoding should match to same object"); }
### Question: ShortString implements EncodableData { @Override public String toString() { return new String(content, StandardCharsets.UTF_8); } @SuppressFBWarnings("EI_EXPOSE_REP2") ShortString(long length, byte[] content); long getSize(); void write(ByteBuf buf); static ShortString parse(ByteBuf buf); static ShortString parseString(String data); @Override String toString(); @Override boolean equals(Object obj); @Override int hashCode(); boolean isEmpty(); }### Answer: @Test public void testToString() throws Exception { Assert.assertEquals(DEFAULT_TEST_OBJECT.toString(), DEFAULT_DATA_STRING, "toString() should match the data " + "string used to create it"); }