method2testcases
stringlengths
118
3.08k
### Question: PendingCheckpoint { public boolean canBeSubsumed() { return !props.forceCheckpoint(); } PendingCheckpoint( JobID jobId, long checkpointId, long checkpointTimestamp, Map<ExecutionAttemptID, ExecutionVertex> verticesToConfirm, CheckpointProperties props, CheckpointStorageLocation targetLocation, Executor executor); JobID getJobId(); long getCheckpointId(); long getCheckpointTimestamp(); int getNumberOfNonAcknowledgedTasks(); int getNumberOfAcknowledgedTasks(); Map<OperatorID, OperatorState> getOperatorStates(); boolean isFullyAcknowledged(); boolean isAcknowledgedBy(ExecutionAttemptID executionAttemptId); boolean isDiscarded(); boolean canBeSubsumed(); boolean setCancellerHandle(ScheduledFuture<?> cancellerHandle); CompletableFuture<CompletedCheckpoint> getCompletionFuture(); CompletedCheckpoint finalizeCheckpoint(); TaskAcknowledgeResult acknowledgeTask( ExecutionAttemptID executionAttemptId, TaskStateSnapshot operatorSubtaskStates, CheckpointMetrics metrics); void addMasterState(MasterState state); void abortExpired(); void abortSubsumed(); void abortDeclined(); void abortError(Throwable cause); @Override String toString(); }### Answer: @Test public void testCanBeSubsumed() throws Exception { CheckpointProperties forced = new CheckpointProperties(true, CheckpointType.SAVEPOINT, false, false, false, false, false); PendingCheckpoint pending = createPendingCheckpoint(forced); assertFalse(pending.canBeSubsumed()); try { pending.abortSubsumed(); fail("Did not throw expected Exception"); } catch (IllegalStateException ignored) { } CheckpointProperties subsumed = new CheckpointProperties(false, CheckpointType.SAVEPOINT, false, false, false, false, false); pending = createPendingCheckpoint(subsumed); assertTrue(pending.canBeSubsumed()); }
### Question: SimpleHttpFacade implements OIDCHttpFacade { @Override public KeycloakSecurityContext getSecurityContext() { SecurityContext context = SecurityContextHolder.getContext(); if (context != null && context.getAuthentication() != null) { KeycloakAuthenticationToken authentication = (KeycloakAuthenticationToken) context.getAuthentication(); return authentication.getAccount().getKeycloakSecurityContext(); } return null; } SimpleHttpFacade(HttpServletRequest request, HttpServletResponse response); @Override KeycloakSecurityContext getSecurityContext(); @Override Request getRequest(); @Override Response getResponse(); @Override X509Certificate[] getCertificateChain(); }### Answer: @Test public void shouldRetrieveKeycloakSecurityContext() { SimpleHttpFacade facade = new SimpleHttpFacade(new MockHttpServletRequest(), new MockHttpServletResponse()); assertNotNull(facade.getSecurityContext()); }
### Question: WrappedHttpServletRequest implements Request { @Override public String getMethod() { return request.getMethod(); } WrappedHttpServletRequest(HttpServletRequest request); @Override String getFirstParam(String param); @Override String getMethod(); @Override String getURI(); @Override String getRelativePath(); @Override boolean isSecure(); @Override String getQueryParamValue(String param); @Override Cookie getCookie(String cookieName); @Override String getHeader(String name); @Override List<String> getHeaders(String name); @Override InputStream getInputStream(); @Override InputStream getInputStream(boolean buffered); @Override String getRemoteAddr(); @Override void setError(AuthenticationError error); @Override void setError(LogoutError error); }### Answer: @Test public void testGetMethod() throws Exception { assertNotNull(request.getMethod()); assertEquals(REQUEST_METHOD, request.getMethod()); }
### Question: WrappedHttpServletRequest implements Request { @Override public String getURI() { StringBuffer buf = request.getRequestURL(); if (request.getQueryString() != null) { buf.append('?').append(request.getQueryString()); } return buf.toString(); } WrappedHttpServletRequest(HttpServletRequest request); @Override String getFirstParam(String param); @Override String getMethod(); @Override String getURI(); @Override String getRelativePath(); @Override boolean isSecure(); @Override String getQueryParamValue(String param); @Override Cookie getCookie(String cookieName); @Override String getHeader(String name); @Override List<String> getHeaders(String name); @Override InputStream getInputStream(); @Override InputStream getInputStream(boolean buffered); @Override String getRemoteAddr(); @Override void setError(AuthenticationError error); @Override void setError(LogoutError error); }### Answer: @Test public void testGetURI() throws Exception { assertEquals("https: }
### Question: WrappedHttpServletRequest implements Request { @Override public boolean isSecure() { return request.isSecure(); } WrappedHttpServletRequest(HttpServletRequest request); @Override String getFirstParam(String param); @Override String getMethod(); @Override String getURI(); @Override String getRelativePath(); @Override boolean isSecure(); @Override String getQueryParamValue(String param); @Override Cookie getCookie(String cookieName); @Override String getHeader(String name); @Override List<String> getHeaders(String name); @Override InputStream getInputStream(); @Override InputStream getInputStream(boolean buffered); @Override String getRemoteAddr(); @Override void setError(AuthenticationError error); @Override void setError(LogoutError error); }### Answer: @Test public void testIsSecure() throws Exception { assertTrue(request.isSecure()); }
### Question: WrappedHttpServletRequest implements Request { @Override public String getQueryParamValue(String param) { return request.getParameter(param); } WrappedHttpServletRequest(HttpServletRequest request); @Override String getFirstParam(String param); @Override String getMethod(); @Override String getURI(); @Override String getRelativePath(); @Override boolean isSecure(); @Override String getQueryParamValue(String param); @Override Cookie getCookie(String cookieName); @Override String getHeader(String name); @Override List<String> getHeaders(String name); @Override InputStream getInputStream(); @Override InputStream getInputStream(boolean buffered); @Override String getRemoteAddr(); @Override void setError(AuthenticationError error); @Override void setError(LogoutError error); }### Answer: @Test public void testGetQueryParamValue() throws Exception { assertNotNull(request.getQueryParamValue(QUERY_PARM_1)); assertNotNull(request.getQueryParamValue(QUERY_PARM_2)); }
### Question: WrappedHttpServletRequest implements Request { @Override public Cookie getCookie(String cookieName) { javax.servlet.http.Cookie[] cookies = request.getCookies(); if (cookies == null) { return null; } for (javax.servlet.http.Cookie cookie : request.getCookies()) { if (cookie.getName().equals(cookieName)) { return new Cookie(cookie.getName(), cookie.getValue(), cookie.getVersion(), cookie.getDomain(), cookie.getPath()); } } return null; } WrappedHttpServletRequest(HttpServletRequest request); @Override String getFirstParam(String param); @Override String getMethod(); @Override String getURI(); @Override String getRelativePath(); @Override boolean isSecure(); @Override String getQueryParamValue(String param); @Override Cookie getCookie(String cookieName); @Override String getHeader(String name); @Override List<String> getHeaders(String name); @Override InputStream getInputStream(); @Override InputStream getInputStream(boolean buffered); @Override String getRemoteAddr(); @Override void setError(AuthenticationError error); @Override void setError(LogoutError error); }### Answer: @Test public void testGetCookie() throws Exception { assertNotNull(request.getCookie(COOKIE_NAME)); } @Test public void testGetCookieCookiesNull() throws Exception { mockHttpServletRequest.setCookies(null); request.getCookie(COOKIE_NAME); }
### Question: WrappedHttpServletRequest implements Request { @Override public String getHeader(String name) { return request.getHeader(name); } WrappedHttpServletRequest(HttpServletRequest request); @Override String getFirstParam(String param); @Override String getMethod(); @Override String getURI(); @Override String getRelativePath(); @Override boolean isSecure(); @Override String getQueryParamValue(String param); @Override Cookie getCookie(String cookieName); @Override String getHeader(String name); @Override List<String> getHeaders(String name); @Override InputStream getInputStream(); @Override InputStream getInputStream(boolean buffered); @Override String getRemoteAddr(); @Override void setError(AuthenticationError error); @Override void setError(LogoutError error); }### Answer: @Test public void testGetHeader() throws Exception { String header = request.getHeader(HEADER_SINGLE_VALUE); assertNotNull(header); assertEquals("baz", header); }
### Question: WrappedHttpServletRequest implements Request { @Override public List<String> getHeaders(String name) { Enumeration<String> values = request.getHeaders(name); List<String> array = new ArrayList<String>(); while (values.hasMoreElements()) { array.add(values.nextElement()); } return Collections.unmodifiableList(array); } WrappedHttpServletRequest(HttpServletRequest request); @Override String getFirstParam(String param); @Override String getMethod(); @Override String getURI(); @Override String getRelativePath(); @Override boolean isSecure(); @Override String getQueryParamValue(String param); @Override Cookie getCookie(String cookieName); @Override String getHeader(String name); @Override List<String> getHeaders(String name); @Override InputStream getInputStream(); @Override InputStream getInputStream(boolean buffered); @Override String getRemoteAddr(); @Override void setError(AuthenticationError error); @Override void setError(LogoutError error); }### Answer: @Test public void testGetHeaders() throws Exception { List<String> headers = request.getHeaders(HEADER_MULTI_VALUE); assertNotNull(headers); assertEquals(2, headers.size()); assertTrue(headers.contains("foo")); assertTrue(headers.contains("bar")); }
### Question: WrappedHttpServletRequest implements Request { @Override public InputStream getInputStream() { return getInputStream(false); } WrappedHttpServletRequest(HttpServletRequest request); @Override String getFirstParam(String param); @Override String getMethod(); @Override String getURI(); @Override String getRelativePath(); @Override boolean isSecure(); @Override String getQueryParamValue(String param); @Override Cookie getCookie(String cookieName); @Override String getHeader(String name); @Override List<String> getHeaders(String name); @Override InputStream getInputStream(); @Override InputStream getInputStream(boolean buffered); @Override String getRemoteAddr(); @Override void setError(AuthenticationError error); @Override void setError(LogoutError error); }### Answer: @Test public void testGetInputStream() throws Exception { assertNotNull(request.getInputStream()); }
### Question: WrappedHttpServletRequest implements Request { @Override public String getRemoteAddr() { return request.getRemoteAddr(); } WrappedHttpServletRequest(HttpServletRequest request); @Override String getFirstParam(String param); @Override String getMethod(); @Override String getURI(); @Override String getRelativePath(); @Override boolean isSecure(); @Override String getQueryParamValue(String param); @Override Cookie getCookie(String cookieName); @Override String getHeader(String name); @Override List<String> getHeaders(String name); @Override InputStream getInputStream(); @Override InputStream getInputStream(boolean buffered); @Override String getRemoteAddr(); @Override void setError(AuthenticationError error); @Override void setError(LogoutError error); }### Answer: @Test public void testGetRemoteAddr() throws Exception { assertNotNull(request.getRemoteAddr()); }
### Question: KeycloakClientRequestFactory extends HttpComponentsClientHttpRequestFactory implements ClientHttpRequestFactory { @Override protected void postProcessHttpRequest(HttpUriRequest request) { KeycloakSecurityContext context = this.getKeycloakSecurityContext(); request.setHeader(AUTHORIZATION_HEADER, "Bearer " + context.getTokenString()); } KeycloakClientRequestFactory(); static final String AUTHORIZATION_HEADER; }### Answer: @Test public void testPostProcessHttpRequest() throws Exception { factory.postProcessHttpRequest(request); verify(factory).getKeycloakSecurityContext(); verify(request).setHeader(eq(KeycloakClientRequestFactory.AUTHORIZATION_HEADER), eq("Bearer " + bearerTokenString)); }
### Question: KeycloakClientRequestFactory extends HttpComponentsClientHttpRequestFactory implements ClientHttpRequestFactory { protected KeycloakSecurityContext getKeycloakSecurityContext() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); KeycloakAuthenticationToken token; KeycloakSecurityContext context; if (authentication == null) { throw new IllegalStateException("Cannot set authorization header because there is no authenticated principal"); } if (!KeycloakAuthenticationToken.class.isAssignableFrom(authentication.getClass())) { throw new IllegalStateException( String.format( "Cannot set authorization header because Authentication is of type %s but %s is required", authentication.getClass(), KeycloakAuthenticationToken.class) ); } token = (KeycloakAuthenticationToken) authentication; context = token.getAccount().getKeycloakSecurityContext(); return context; } KeycloakClientRequestFactory(); static final String AUTHORIZATION_HEADER; }### Answer: @Test public void testGetKeycloakSecurityContext() throws Exception { KeycloakSecurityContext context = factory.getKeycloakSecurityContext(); assertNotNull(context); assertEquals(keycloakSecurityContext, context); } @Test(expected = IllegalStateException.class) public void testGetKeycloakSecurityContextInvalidAuthentication() throws Exception { SecurityContextHolder.getContext().setAuthentication( new PreAuthenticatedAuthenticationToken("foo", "bar", Collections.singleton(new KeycloakRole("baz")))); factory.getKeycloakSecurityContext(); } @Test(expected = IllegalStateException.class) public void testGetKeycloakSecurityContextNullAuthentication() throws Exception { SecurityContextHolder.clearContext(); factory.getKeycloakSecurityContext(); }
### Question: JBossWebPrincipalFactory extends GenericPrincipalFactory { static Constructor findJBossGenericPrincipalConstructor() { for (Constructor<?> c : JBossGenericPrincipal.class.getConstructors()) { if (c.getParameterTypes().length == 9 && c.getParameterTypes()[0].equals(Realm.class) && c.getParameterTypes()[1].equals(String.class) && c.getParameterTypes()[3].equals(List.class) && c.getParameterTypes()[4].equals(Principal.class) && c.getParameterTypes()[6].equals(Object.class) && c.getParameterTypes()[8].equals(Subject.class)) { return c; } } return null; } @Override GenericPrincipal createPrincipal(Realm realm, final Principal identity, final Set<String> roleSet); }### Answer: @Test public void test() { Constructor constructor = JBossWebPrincipalFactory.findJBossGenericPrincipalConstructor(); Assert.assertNotNull(constructor); Assert.assertEquals(Realm.class, constructor.getParameterTypes()[0]); Assert.assertEquals(String.class, constructor.getParameterTypes()[1]); Assert.assertEquals(List.class, constructor.getParameterTypes()[3]); Assert.assertEquals(Principal.class, constructor.getParameterTypes()[4]); Assert.assertEquals(Object.class, constructor.getParameterTypes()[6]); Assert.assertEquals(Subject.class, constructor.getParameterTypes()[8]); }
### Question: KeycloakSecurityContextClientRequestInterceptor implements ClientHttpRequestInterceptor { protected KeycloakSecurityContext getKeycloakSecurityContext() { ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); Principal principal = attributes.getRequest().getUserPrincipal(); if (principal == null) { throw new IllegalStateException("Cannot set authorization header because there is no authenticated principal"); } if (!(principal instanceof KeycloakPrincipal)) { throw new IllegalStateException( String.format( "Cannot set authorization header because the principal type %s does not provide the KeycloakSecurityContext", principal.getClass())); } return ((KeycloakPrincipal) principal).getKeycloakSecurityContext(); } @Override ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution); }### Answer: @Test public void testGetKeycloakSecurityContext() throws Exception { KeycloakSecurityContext context = factory.getKeycloakSecurityContext(); assertNotNull(context); assertEquals(keycloakSecurityContext, context); } @Test(expected = IllegalStateException.class) public void testGetKeycloakSecurityContextInvalidPrincipal() throws Exception { servletRequest.setUserPrincipal(new MarkerPrincipal()); factory.getKeycloakSecurityContext(); } @Test(expected = IllegalStateException.class) public void testGetKeycloakSecurityContextNullAuthentication() throws Exception { servletRequest.setUserPrincipal(null); factory.getKeycloakSecurityContext(); }
### Question: KeycloakRestTemplateCustomizer implements RestTemplateCustomizer { @Override public void customize(RestTemplate restTemplate) { restTemplate.getInterceptors().add(keycloakInterceptor); } KeycloakRestTemplateCustomizer(); protected KeycloakRestTemplateCustomizer( KeycloakSecurityContextClientRequestInterceptor keycloakInterceptor ); @Override void customize(RestTemplate restTemplate); }### Answer: @Test public void interceptorIsAddedToRequest() { RestTemplate restTemplate = new RestTemplate(); customizer.customize(restTemplate); assertTrue(restTemplate.getInterceptors().contains(interceptor)); }
### Question: HierarchicalPathBasedKeycloakConfigResolver extends PathBasedKeycloakConfigResolver { @Override public KeycloakDeployment resolve(OIDCHttpFacade.Request request) { URI uri = URI.create(request.getURI()); String path = uri.getPath(); if (path != null) { while (path.startsWith("/")) { path = path.substring(1); } String[] segments = path.split("/"); List<String> paths = collectPaths(segments); for (String pathFragment: paths) { KeycloakDeployment cachedDeployment = super.getCachedDeployment(pathFragment); if (cachedDeployment != null) { return cachedDeployment; } } } throw new IllegalStateException("Can't find Keycloak configuration related to URI path " + uri); } HierarchicalPathBasedKeycloakConfigResolver(); @Override KeycloakDeployment resolve(OIDCHttpFacade.Request request); }### Answer: @Test public void genericAndSpecificConfigurations() throws Exception { HierarchicalPathBasedKeycloakConfigResolver resolver = new HierarchicalPathBasedKeycloakConfigResolver(); populate(resolver, true); assertThat(resolver.resolve(new MockRequest("http: assertThat(resolver.resolve(new MockRequest("http: assertThat(resolver.resolve(new MockRequest("http: assertThat(resolver.resolve(new MockRequest("http: assertThat(resolver.resolve(new MockRequest("http: assertThat(resolver.resolve(new MockRequest("http: populate(resolver, false); try { resolver.resolve(new MockRequest("http: fail("Expected java.lang.IllegalStateException: Can't find Keycloak configuration ..."); } catch (IllegalStateException expected) { } }
### Question: PathBasedKeycloakConfigResolver implements KeycloakConfigResolver { @Override public KeycloakDeployment resolve(OIDCHttpFacade.Request request) { String webContext = getDeploymentKeyForURI(request); return getOrCreateDeployment(webContext); } PathBasedKeycloakConfigResolver(); @Override KeycloakDeployment resolve(OIDCHttpFacade.Request request); }### Answer: @Test public void relativeURIsAndContexts() throws Exception { PathBasedKeycloakConfigResolver resolver = new PathBasedKeycloakConfigResolver(); assertNotNull(populate(resolver, "test") .resolve(new MockRequest("http: assertNotNull(populate(resolver, "test") .resolve(new MockRequest("http: assertNotNull(populate(resolver, "test") .resolve(new MockRequest("http: assertNotNull(populate(resolver, "test/a") .resolve(new MockRequest("http: assertNotNull(populate(resolver, "") .resolve(new MockRequest("http: }
### Question: RefreshableKeycloakSecurityContext extends KeycloakSecurityContext { public boolean isActive() { return token != null && this.token.isActive() && deployment!=null && this.token.getIssuedAt() >= deployment.getNotBefore(); } RefreshableKeycloakSecurityContext(); RefreshableKeycloakSecurityContext(KeycloakDeployment deployment, AdapterTokenStore tokenStore, String tokenString, AccessToken token, String idTokenString, IDToken idToken, String refreshToken); @Override AccessToken getToken(); @Override String getTokenString(); @Override IDToken getIdToken(); @Override String getIdTokenString(); String getRefreshToken(); void logout(KeycloakDeployment deployment); boolean isActive(); boolean isTokenTimeToLiveSufficient(AccessToken token); KeycloakDeployment getDeployment(); void setCurrentRequestInfo(KeycloakDeployment deployment, AdapterTokenStore tokenStore); boolean refreshExpiredToken(boolean checkActive); void setAuthorizationContext(AuthorizationContext authorizationContext); }### Answer: @Test public void isActive() { TokenMetadataRepresentation token = new TokenMetadataRepresentation(); token.setActive(true); token.issuedNow(); RefreshableKeycloakSecurityContext sut = new RefreshableKeycloakSecurityContext(null,null,null,token,null, null, null); assertFalse(sut.isActive()); } @Test public void sameIssuedAtAsNotBeforeIsActiveKEYCLOAK10013() { KeycloakDeployment keycloakDeployment = new KeycloakDeployment(); keycloakDeployment.setNotBefore(5000); TokenMetadataRepresentation token = new TokenMetadataRepresentation(); token.setActive(true); token.issuedAt(4999); RefreshableKeycloakSecurityContext sut = new RefreshableKeycloakSecurityContext(keycloakDeployment,null,null,token,null, null, null); assertFalse(sut.isActive()); token.issuedAt(5000); assertTrue(sut.isActive()); }
### Question: IDFedLSInputResolver implements LSResourceResolver { public IDFedLSInput resolveResource(String type, String namespaceURI, final String publicId, final String systemId, final String baseURI) { if (systemId == null) { throw new IllegalArgumentException("Expected systemId"); } final String loc = schemaLocationMap.get(systemId); if (loc == null) { return null; } return new IDFedLSInput(baseURI, loc, publicId, systemId); } static Collection<String> schemas(); IDFedLSInput resolveResource(String type, String namespaceURI, final String publicId, final String systemId, final String baseURI); }### Answer: @Test public void testSchemaConstruction() throws Exception { SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); final IDFedLSInputResolver idFedLSInputResolver = new IDFedLSInputResolver(); schemaFactory.setResourceResolver(new LSResourceResolver() { @Override public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) { LSInput input = idFedLSInputResolver.resolveResource(type, namespaceURI, publicId, systemId, baseURI); if(input == null) { throw new IllegalArgumentException("Unable to resolve " + systemId); } InputStream is = input.getByteStream(); if(is == null) { throw new IllegalArgumentException("Unable to resolve stream for " + systemId); } try { is.close(); } catch (IOException e) { throw new RuntimeException(e); } return input; } }); for(String schema : SchemaManagerUtil.getSchemas()) { if(schema.contains("saml")) { URL schemaFile = SecurityActions.loadResource(getClass(), schema); schemaFactory.newSchema(schemaFile); } } JAXPValidationUtil.validator(); }
### Question: SecurityActions { public static Class<?> loadClass(final Class<?> theClass, final String fullQualifiedName) { SecurityManager sm = System.getSecurityManager(); if (fullQualifiedName == null) { return null; } if (sm != null) { sm.checkPackageDefinition(extractPackageNameFromClassName(fullQualifiedName)); return AccessController.doPrivileged(new PrivilegedAction<Class<?>>() { @Override public Class<?> run() { ClassLoader classLoader = theClass.getClassLoader(); Class<?> clazz = loadClass(classLoader, fullQualifiedName); if (clazz == null) { classLoader = Thread.currentThread().getContextClassLoader(); clazz = loadClass(classLoader, fullQualifiedName); } return clazz; } }); } else { ClassLoader classLoader = theClass.getClassLoader(); Class<?> clazz = loadClass(classLoader, fullQualifiedName); if (clazz == null) { classLoader = Thread.currentThread().getContextClassLoader(); clazz = loadClass(classLoader, fullQualifiedName); } return clazz; } } static Class<?> loadClass(final Class<?> theClass, final String fullQualifiedName); static Class<?> loadClass(final ClassLoader classLoader, final String fullQualifiedName); static URL loadResource(final Class<?> clazz, final String resourceName); static void setSystemProperty(final String key, final String value); static String getSystemProperty(final String key, final String defaultValue); static ClassLoader getTCCL(); static void setTCCL(final ClassLoader paramCl); }### Answer: @Test public void testLoadClass() { SecurityActions.loadClass(SecurityActionsTest.class, "java.lang.String"); if (RESTRICTED) { expectedException.expect(SecurityException.class); } SecurityActions.loadClass(SecurityActions.class, "sun.misc.Unsafe"); }
### Question: SecurityActions { public static ClassLoader getTCCL() { if (System.getSecurityManager() != null) { System.getSecurityManager().checkPermission(new RuntimePermission("getClassLoader")); return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() { @Override public ClassLoader run() { return Thread.currentThread().getContextClassLoader(); } }); } else { return Thread.currentThread().getContextClassLoader(); } } static Class<?> loadClass(final Class<?> theClass, final String fullQualifiedName); static Class<?> loadClass(final ClassLoader classLoader, final String fullQualifiedName); static URL loadResource(final Class<?> clazz, final String resourceName); static void setSystemProperty(final String key, final String value); static String getSystemProperty(final String key, final String defaultValue); static ClassLoader getTCCL(); static void setTCCL(final ClassLoader paramCl); }### Answer: @Test public void testGetTCCL() { if (RESTRICTED) { expectedException.expect(AccessControlException.class); } SecurityActions.getTCCL(); }
### Question: SecurityActions { public static void setTCCL(final ClassLoader paramCl) { if (System.getSecurityManager() != null) { System.getSecurityManager().checkPermission(new RuntimePermission("setContextClassLoader")); AccessController.doPrivileged(new PrivilegedAction<Void>() { @Override public Void run() { Thread.currentThread().setContextClassLoader(paramCl); return null; } }); } else { Thread.currentThread().setContextClassLoader(paramCl); } } static Class<?> loadClass(final Class<?> theClass, final String fullQualifiedName); static Class<?> loadClass(final ClassLoader classLoader, final String fullQualifiedName); static URL loadResource(final Class<?> clazz, final String resourceName); static void setSystemProperty(final String key, final String value); static String getSystemProperty(final String key, final String defaultValue); static ClassLoader getTCCL(); static void setTCCL(final ClassLoader paramCl); }### Answer: @Test public void testSetTCCL() { if (RESTRICTED) { expectedException.expect(AccessControlException.class); } SecurityActions.setTCCL(ClassLoader.getSystemClassLoader()); }
### Question: ReturnFields implements Iterable<String> { @Override public String toString() { return "[ReturnFieldsImpl: fields=" + this.fields + "]"; } ReturnFields(); ReturnFields(String spec); ReturnFields child(String field); boolean included(String... pathSegments); boolean excluded(String field); Iterator<String> iterator(); boolean isEmpty(); boolean isAll(); @Override String toString(); static ReturnFields ALL; static ReturnFields NONE; static ReturnFields ALL_RECURSIVELY; }### Answer: @Test public void testBasic() { String spec = "field1,field2,field3"; ReturnFields fspec = new ReturnFields(spec); StringBuilder val = new StringBuilder(); for (String field : fspec) { if (val.length() > 0) val.append(','); val.append(field); } Assert.assertEquals(spec, val.toString()); String[] specs = { "", null, ",", "field1,", ",field2" }; for (String filter : specs) { try { fspec = new ReturnFields(filter); Assert.fail("Parsing of fields spec should have failed! : " + filter); } catch (Exception e) { } } } @Test public void testNested() { String spec = "field1,field2(sub1,sub2(subsub1)),field3"; ReturnFields fspec = new ReturnFields(spec); String val = traverse(fspec); Assert.assertEquals(spec, val.toString()); String[] specs = { "(", ")", "field1,(", "field1,)", "field1,field2(", "field1,field2)", "field1,field2()", "field1,field2(sub1)(", "field1,field2(sub1))", "field1,field2(sub1)," }; for (String filter : specs) { try { fspec = new ReturnFields(filter); Assert.fail("Parsing of fields spec should have failed! : " + filter); } catch (Exception e) { } } }
### Question: StringPropertyReplacer { public static String replaceProperties(final String string) { return replaceProperties(string, (Properties) null); } static String replaceProperties(final String string); static String replaceProperties(final String string, final Properties props); static String replaceProperties(final String string, PropertyResolver resolver); static final String NEWLINE; }### Answer: @Test public void testSystemProperties() throws NoSuchAlgorithmException { System.setProperty("prop1", "val1"); Assert.assertEquals("foo-val1", StringPropertyReplacer.replaceProperties("foo-${prop1}")); Assert.assertEquals("foo-def", StringPropertyReplacer.replaceProperties("foo-${prop2:def}")); System.setProperty("prop2", "val2"); Assert.assertEquals("foo-val2", StringPropertyReplacer.replaceProperties("foo-${prop2:def}")); Assert.assertEquals("foo-def", StringPropertyReplacer.replaceProperties("foo-${prop3:${prop4:${prop5:def}}}")); System.setProperty("prop5", "val5"); Assert.assertEquals("foo-val5", StringPropertyReplacer.replaceProperties("foo-${prop3:${prop4:${prop5:def}}}")); System.setProperty("prop4", "val4"); Assert.assertEquals("foo-val4", StringPropertyReplacer.replaceProperties("foo-${prop3:${prop4:${prop5:def}}}")); System.setProperty("prop3", "val3"); Assert.assertEquals("foo-val3", StringPropertyReplacer.replaceProperties("foo-${prop3:${prop4:${prop5:def}}}")); Assert.assertEquals("foo-def", StringPropertyReplacer.replaceProperties("foo-${prop6,prop7:def}")); System.setProperty("prop7", "val7"); Assert.assertEquals("foo-val7", StringPropertyReplacer.replaceProperties("foo-${prop6,prop7:def}")); System.setProperty("prop6", "val6"); Assert.assertEquals("foo-val6", StringPropertyReplacer.replaceProperties("foo-${prop6,prop7:def}")); }
### Question: HtmlUtils { public static String escapeAttribute(String value) { StringBuilder escaped = new StringBuilder(); for (int i = 0; i < value.length(); i++) { char chr = value.charAt(i); if (chr == '<') { escaped.append("&lt;"); } else if (chr == '>') { escaped.append("&gt;"); } else if (chr == '"') { escaped.append("&quot;"); } else if (chr == '\'') { escaped.append("&apos;"); } else if (chr == '&') { escaped.append("&amp;"); } else { escaped.append(chr); } } return escaped.toString(); } static String escapeAttribute(String value); }### Answer: @Test public void escapeAttribute() { Assert.assertEquals("1&lt;2", HtmlUtils.escapeAttribute("1<2")); Assert.assertEquals("2&lt;3&amp;&amp;3&gt;2", HtmlUtils.escapeAttribute("2<3&&3>2") ); Assert.assertEquals("test", HtmlUtils.escapeAttribute("test")); Assert.assertEquals("&apos;test&apos;", HtmlUtils.escapeAttribute("\'test\'")); Assert.assertEquals("&quot;test&quot;", HtmlUtils.escapeAttribute("\"test\"")); }
### Question: CollectionUtil { public static String join(Collection<String> strings) { return join(strings, ", "); } static String join(Collection<String> strings); static String join(Collection<String> strings, String separator); static boolean collectionEquals(Collection<T> col1, Collection<T> col2); }### Answer: @Test public void joinInputNoneOutputEmpty() { final ArrayList<String> strings = new ArrayList<>(); final String retval = CollectionUtil.join(strings, ","); Assert.assertEquals("", retval); } @Test public void joinInput2SeparatorNull() { final ArrayList<String> strings = new ArrayList<>(); strings.add("foo"); strings.add("bar"); final String retval = CollectionUtil.join(strings, null); Assert.assertEquals("foonullbar", retval); } @Test public void joinInput1SeparatorNotNull() { final ArrayList<String> strings = new ArrayList<>(); strings.add("foo"); final String retval = CollectionUtil.join(strings, ","); Assert.assertEquals("foo", retval); } @Test public void joinInput2SeparatorNotNull() { final ArrayList<String> strings = new ArrayList<>(); strings.add("foo"); strings.add("bar"); final String retval = CollectionUtil.join(strings, ","); Assert.assertEquals("foo,bar", retval); }
### Question: KeyUtils { public static SecretKey loadSecretKey(byte[] secret, String javaAlgorithmName) { return new SecretKeySpec(secret, javaAlgorithmName); } private KeyUtils(); static SecretKey loadSecretKey(byte[] secret, String javaAlgorithmName); static KeyPair generateRsaKeyPair(int keysize); static PublicKey extractPublicKey(PrivateKey key); static String createKeyId(Key key); }### Answer: @Test public void loadSecretKey() { byte[] secretBytes = new byte[32]; ThreadLocalRandom.current().nextBytes(secretBytes); SecretKeySpec expected = new SecretKeySpec(secretBytes, "HmacSHA256"); SecretKey actual = KeyUtils.loadSecretKey(secretBytes, "HmacSHA256"); assertEquals(expected.getAlgorithm(), actual.getAlgorithm()); assertArrayEquals(expected.getEncoded(), actual.getEncoded()); }
### Question: PemUtils { static byte[] generateThumbprintBytes(String[] certChain, String encoding) throws NoSuchAlgorithmException { return MessageDigest.getInstance(encoding).digest(pemToDer(certChain[0])); } private PemUtils(); static X509Certificate decodeCertificate(String cert); static PublicKey decodePublicKey(String pem); static PrivateKey decodePrivateKey(String pem); static String encodeKey(Key key); static String encodeCertificate(Certificate certificate); static byte[] pemToDer(String pem); static String removeBeginEnd(String pem); static String generateThumbprint(String[] certChain, String encoding); }### Answer: @Test public void testGenerateThumbprintBytesSha1() throws NoSuchAlgorithmException { String[] test = new String[] {"abcdefg"}; byte[] digest = PemUtils.generateThumbprintBytes(test, "SHA-1"); assertEquals(20, digest.length); } @Test public void testGenerateThumbprintBytesSha256() throws NoSuchAlgorithmException { String[] test = new String[] {"abcdefg"}; byte[] digest = PemUtils.generateThumbprintBytes(test, "SHA-256"); assertEquals(32, digest.length); }
### Question: PemUtils { public static String generateThumbprint(String[] certChain, String encoding) throws NoSuchAlgorithmException { return Base64Url.encode(generateThumbprintBytes(certChain, encoding)); } private PemUtils(); static X509Certificate decodeCertificate(String cert); static PublicKey decodePublicKey(String pem); static PrivateKey decodePrivateKey(String pem); static String encodeKey(Key key); static String encodeCertificate(Certificate certificate); static byte[] pemToDer(String pem); static String removeBeginEnd(String pem); static String generateThumbprint(String[] certChain, String encoding); }### Answer: @Test public void testGenerateThumbprintSha1() throws NoSuchAlgorithmException { String[] test = new String[] {"abcdefg"}; String encoded = PemUtils.generateThumbprint(test, "SHA-1"); assertEquals(27, encoded.length()); } @Test public void testGenerateThumbprintSha256() throws NoSuchAlgorithmException { String[] test = new String[] {"abcdefg"}; String encoded = PemUtils.generateThumbprint(test, "SHA-256"); assertEquals(43, encoded.length()); }
### Question: RegexUtils { public static boolean valueMatchesRegex(String regex, Object value) { if (value instanceof List) { List list = (List) value; for (Object val : list) { if (valueMatchesRegex(regex, val)) { return true; } } } else { if (value != null) { String stringValue = value.toString(); return stringValue != null && stringValue.matches(regex); } } return false; } static boolean valueMatchesRegex(String regex, Object value); }### Answer: @Test public void valueMatchesRegexTest() { assertThat(RegexUtils.valueMatchesRegex("AB.*", "AB_ADMIN"), is(true)); assertThat(RegexUtils.valueMatchesRegex("AB.*", "AA_ADMIN"), is(false)); assertThat(RegexUtils.valueMatchesRegex("99.*", 999), is(true)); assertThat(RegexUtils.valueMatchesRegex("98.*", 999), is(false)); assertThat(RegexUtils.valueMatchesRegex("99\\..*", 99.9), is(true)); assertThat(RegexUtils.valueMatchesRegex("AB.*", null), is(false)); assertThat(RegexUtils.valueMatchesRegex("AB.*", Arrays.asList("AB_ADMIN", "AA_ADMIN")), is(true)); }
### Question: JWK { public String getAlgorithm() { return algorithm; } String getKeyId(); void setKeyId(String keyId); String getKeyType(); void setKeyType(String keyType); String getAlgorithm(); void setAlgorithm(String algorithm); String getPublicKeyUse(); void setPublicKeyUse(String publicKeyUse); @JsonAnyGetter Map<String, Object> getOtherClaims(); @JsonAnySetter void setOtherClaims(String name, Object value); static final String KEY_ID; static final String KEY_TYPE; static final String ALGORITHM; static final String PUBLIC_KEY_USE; }### Answer: @Test public void parse() { String jwkJson = "{" + " \"kty\": \"RSA\"," + " \"alg\": \"RS256\"," + " \"use\": \"sig\"," + " \"kid\": \"3121adaa80ace09f89d80899d4a5dc4ce33d0747\"," + " \"n\": \"soFDjoZ5mQ8XAA7reQAFg90inKAHk0DXMTizo4JuOsgzUbhcplIeZ7ks83hsEjm8mP8lUVaHMPMAHEIp3gu6Xxsg-s73ofx1dtt_Fo7aj8j383MFQGl8-FvixTVobNeGeC0XBBQjN8lEl-lIwOa4ZoERNAShplTej0ntDp7TQm0=\"," + " \"e\": \"AQAB\"" + " }"; PublicKey key = JWKParser.create().parse(jwkJson).toPublicKey(); assertEquals("RSA", key.getAlgorithm()); assertEquals("X.509", key.getFormat()); }
### Question: PropertiesUtil { public static Charset detectEncoding(InputStream in) throws IOException { try (BufferedReader br = new BufferedReader(new InputStreamReader(in, DEFAULT_ENCODING))) { String firstLine = br.readLine(); if (firstLine != null) { Matcher matcher = DETECT_ENCODING_PATTERN.matcher(firstLine); if (matcher.find()) { String encoding = matcher.group(1); if (Charset.isSupported(encoding)) { return Charset.forName(encoding); } else { logger.warnv("Unsupported encoding: {0}", encoding); } } } } return DEFAULT_ENCODING; } static Charset detectEncoding(InputStream in); static final Pattern DETECT_ENCODING_PATTERN; static final Charset DEFAULT_ENCODING; }### Answer: @Test public void testDetectEncoding() throws Exception { Charset encoding = PropertiesUtil.detectEncoding(new ByteArrayInputStream("# encoding: utf-8\nkey=value".getBytes())); assertEquals(Charset.forName("utf-8"), encoding); encoding = PropertiesUtil.detectEncoding(new ByteArrayInputStream("# encoding: Shift_JIS\nkey=value".getBytes())); assertEquals(Charset.forName("Shift_JIS"), encoding); } @Test public void testDefaultEncoding() throws Exception { Charset encoding = PropertiesUtil.detectEncoding(new ByteArrayInputStream("key=value".getBytes())); assertEquals(Charset.forName("ISO-8859-1"), encoding); encoding = PropertiesUtil.detectEncoding(new ByteArrayInputStream("# encoding: unknown\nkey=value".getBytes())); assertEquals(Charset.forName("ISO-8859-1"), encoding); encoding = PropertiesUtil.detectEncoding(new ByteArrayInputStream("\n# encoding: utf-8\nkey=value".getBytes())); assertEquals(Charset.forName("ISO-8859-1"), encoding); encoding = PropertiesUtil.detectEncoding(new ByteArrayInputStream("".getBytes())); assertEquals(Charset.forName("ISO-8859-1"), encoding); }
### Question: KeyPairVerifier { public static void verify(String privateKeyPem, String publicKeyPem) throws VerificationException { PrivateKey privateKey; try { privateKey = PemUtils.decodePrivateKey(privateKeyPem); } catch (Exception e) { throw new VerificationException("Failed to decode private key"); } PublicKey publicKey; try { publicKey = PemUtils.decodePublicKey(publicKeyPem); } catch (Exception e) { throw new VerificationException("Failed to decode public key"); } try { String jws = new JWSBuilder().content("content".getBytes()).rsa256(privateKey); if (!RSAProvider.verify(new JWSInput(jws), publicKey)) { throw new VerificationException("Keys don't match"); } } catch (Exception e) { throw new VerificationException("Keys don't match"); } } static void verify(String privateKeyPem, String publicKeyPem); }### Answer: @Test public void verify() throws Exception { KeyPairVerifier.verify(privateKey1, publicKey1); KeyPairVerifier.verify(privateKey2048, publicKey2048); try { KeyPairVerifier.verify(privateKey1, publicKey2048); Assert.fail("Expected VerificationException"); } catch (VerificationException e) { } try { KeyPairVerifier.verify(privateKey2048, publicKey1); Assert.fail("Expected VerificationException"); } catch (VerificationException e) { } }
### Question: MessageFormatterMethod implements TemplateMethodModelEx { @Override public Object exec(List list) throws TemplateModelException { if (list.size() >= 1) { List<Object> resolved = resolve(list.subList(1, list.size())); String key = list.get(0).toString(); return new MessageFormat(messages.getProperty(key,key),locale).format(resolved.toArray()); } else { return null; } } MessageFormatterMethod(Locale locale, Properties messages); @Override Object exec(List list); }### Answer: @Test public void test() throws TemplateModelException { Locale locale = Locale.US; Properties properties = new Properties(); properties.setProperty("backToApplication", "Back to application"); properties.setProperty("backToClient", "Back to {0}"); properties.setProperty("client_admin-console", "Admin Console"); properties.setProperty("realm_example-realm", "Example Realm"); MessageFormatterMethod fmt = new MessageFormatterMethod(locale, properties); String msg = (String) fmt.exec(Arrays.asList("backToClient", "${client_admin-console}")); Assert.assertEquals("Back to Admin Console", msg); msg = (String) fmt.exec(Arrays.asList("backToClient", "client_admin-console")); Assert.assertEquals("Back to client_admin-console", msg); msg = (String) fmt.exec(Arrays.asList("backToClient", "client '${client_admin-console}' from '${realm_example-realm}'.")); Assert.assertEquals("Back to client 'Admin Console' from 'Example Realm'.", msg); }
### Question: InitializerState extends SessionEntity { public int getSegmentsCount() { return segmentsCount; } InitializerState(int segmentsCount); private InitializerState(String realmId, int segmentsCount, BitSet segments); int getSegmentsCount(); boolean isFinished(); List<Integer> getSegmentsToLoad(int segmentToLoad, int maxSegmentCount); void markSegmentFinished(int index); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testOfflineLoaderContext() { OfflinePersistentLoaderContext ctx = new OfflinePersistentLoaderContext(28, 5); Assert.assertEquals(ctx.getSegmentsCount(), 6); ctx = new OfflinePersistentLoaderContext(19, 5); Assert.assertEquals(ctx.getSegmentsCount(), 4); ctx = new OfflinePersistentLoaderContext(20, 5); Assert.assertEquals(ctx.getSegmentsCount(), 4); ctx = new OfflinePersistentLoaderContext(21, 5); Assert.assertEquals(ctx.getSegmentsCount(), 5); }
### Question: JpaUtils { public static String getCustomChangelogTableName(String jpaEntityProviderFactoryId) { String upperCased = jpaEntityProviderFactoryId.toUpperCase(); upperCased = upperCased.replaceAll("-", "_"); upperCased = upperCased.replaceAll("[^A-Z_]", ""); return "DATABASECHANGELOG_" + upperCased.substring(0, Math.min(10, upperCased.length())); } static String getTableNameForNativeQuery(String tableName, EntityManager em); static EntityManagerFactory createEntityManagerFactory(KeycloakSession session, String unitName, Map<String, Object> properties, boolean jta); static List<Class<?>> getProvidedEntities(KeycloakSession session); static String getCustomChangelogTableName(String jpaEntityProviderFactoryId); static final String HIBERNATE_DEFAULT_SCHEMA; }### Answer: @Test public void testConvertTableName() { Assert.assertEquals("DATABASECHANGELOG_FOO", JpaUtils.getCustomChangelogTableName("foo")); Assert.assertEquals("DATABASECHANGELOG_FOOBAR", JpaUtils.getCustomChangelogTableName("foo123bar")); Assert.assertEquals("DATABASECHANGELOG_FOO_BAR", JpaUtils.getCustomChangelogTableName("foo_bar568")); Assert.assertEquals("DATABASECHANGELOG_FOO_BAR_C", JpaUtils.getCustomChangelogTableName("foo-bar-c568")); Assert.assertEquals("DATABASECHANGELOG_EXAMPLE_EN", JpaUtils.getCustomChangelogTableName("example-entity-provider")); }
### Question: PropertiesBasedRoleMapper implements RoleMappingsProvider { @Override public Set<String> map(final String principalName, final Set<String> roles) { if (this.roleMappings == null || this.roleMappings.isEmpty()) return roles; Set<String> resolvedRoles = new HashSet<>(); for (String role : roles) { if (this.roleMappings.containsKey(role)) { this.extractRolesIntoSet(role, resolvedRoles); } else { resolvedRoles.add(role); } } if (this.roleMappings.containsKey(principalName)) { this.extractRolesIntoSet(principalName, resolvedRoles); } return resolvedRoles; } @Override String getId(); @Override void init(final SamlDeployment deployment, final ResourceLoader loader, final Properties config); @Override Set<String> map(final String principalName, final Set<String> roles); static final String PROVIDER_ID; }### Answer: @Test public void testPropertiesBasedRoleMapper() throws Exception { InputStream is = getClass().getResourceAsStream("config/parsers/keycloak-saml-with-role-mappings-provider.xml"); SamlDeployment deployment = new DeploymentBuilder().build(is, new ResourceLoader() { @Override public InputStream getResourceAsStream(String resource) { return this.getClass().getClassLoader().getResourceAsStream(resource); } }); RoleMappingsProvider provider = deployment.getRoleMappingsProvider(); final Set<String> samlRoles = new HashSet<>(Arrays.asList(new String[]{"samlRoleA", "samlRoleB", "samlRoleC"})); final Set<String> mappedRoles = provider.map("kc-user", samlRoles); assertNotNull(mappedRoles); assertEquals(4, mappedRoles.size()); Set<String> expectedRoles = new HashSet<>(Arrays.asList(new String[]{"samlRoleC", "jeeRoleX", "jeeRoleY", "jeeRoleZ"})); assertEquals(expectedRoles, mappedRoles); }
### Question: HttpHeaderInspectingApiRequestMatcher implements RequestMatcher { @Override public boolean matches(HttpServletRequest request) { return X_REQUESTED_WITH_HEADER_AJAX_VALUE.equals(request.getHeader(X_REQUESTED_WITH_HEADER)); } @Override boolean matches(HttpServletRequest request); }### Answer: @Test public void testMatchesBrowserRequest() throws Exception { request.addHeader(HttpHeaders.ACCEPT, "application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); assertFalse(apiRequestMatcher.matches(request)); } @Test public void testMatchesRequestedWith() throws Exception { request.addHeader( HttpHeaderInspectingApiRequestMatcher.X_REQUESTED_WITH_HEADER, HttpHeaderInspectingApiRequestMatcher.X_REQUESTED_WITH_HEADER_AJAX_VALUE); assertTrue(apiRequestMatcher.matches(request)); }
### Question: SpringSecurityRequestAuthenticator extends RequestAuthenticator { @Override protected OAuthRequestAuthenticator createOAuthAuthenticator() { return new OAuthRequestAuthenticator(this, facade, deployment, sslRedirectPort, tokenStore); } SpringSecurityRequestAuthenticator( HttpFacade facade, HttpServletRequest request, KeycloakDeployment deployment, AdapterTokenStore tokenStore, int sslRedirectPort); }### Answer: @Test public void testCreateOAuthAuthenticator() throws Exception { OAuthRequestAuthenticator oathAuthenticator = authenticator.createOAuthAuthenticator(); assertNotNull(oathAuthenticator); }
### Question: SpringSecurityRequestAuthenticator extends RequestAuthenticator { @Override protected void completeOAuthAuthentication(final KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal) { final RefreshableKeycloakSecurityContext securityContext = principal.getKeycloakSecurityContext(); final Set<String> roles = AdapterUtils.getRolesFromSecurityContext(securityContext); final OidcKeycloakAccount account = new SimpleKeycloakAccount(principal, roles, securityContext); request.setAttribute(KeycloakSecurityContext.class.getName(), securityContext); this.tokenStore.saveAccountInfo(account); } SpringSecurityRequestAuthenticator( HttpFacade facade, HttpServletRequest request, KeycloakDeployment deployment, AdapterTokenStore tokenStore, int sslRedirectPort); }### Answer: @Test public void testCompleteOAuthAuthentication() throws Exception { authenticator.completeOAuthAuthentication(principal); verify(request).setAttribute(eq(KeycloakSecurityContext.class.getName()), eq(refreshableKeycloakSecurityContext)); verify(tokenStore).saveAccountInfo(any(OidcKeycloakAccount.class)); }
### Question: SpringSecurityRequestAuthenticator extends RequestAuthenticator { @Override protected void completeBearerAuthentication(KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal, String method) { RefreshableKeycloakSecurityContext securityContext = principal.getKeycloakSecurityContext(); Set<String> roles = AdapterUtils.getRolesFromSecurityContext(securityContext); final KeycloakAccount account = new SimpleKeycloakAccount(principal, roles, securityContext); logger.debug("Completing bearer authentication. Bearer roles: {} ",roles); SecurityContext context = SecurityContextHolder.createEmptyContext(); context.setAuthentication(new KeycloakAuthenticationToken(account, false)); SecurityContextHolder.setContext(context); request.setAttribute(KeycloakSecurityContext.class.getName(), securityContext); } SpringSecurityRequestAuthenticator( HttpFacade facade, HttpServletRequest request, KeycloakDeployment deployment, AdapterTokenStore tokenStore, int sslRedirectPort); }### Answer: @Test public void testCompleteBearerAuthentication() throws Exception { authenticator.completeBearerAuthentication(principal, "foo"); verify(request).setAttribute(eq(KeycloakSecurityContext.class.getName()), eq(refreshableKeycloakSecurityContext)); assertNotNull(SecurityContextHolder.getContext().getAuthentication()); assertTrue(KeycloakAuthenticationToken.class.isAssignableFrom(SecurityContextHolder.getContext().getAuthentication().getClass())); }
### Question: SpringSecurityRequestAuthenticator extends RequestAuthenticator { @Override protected String changeHttpSessionId(boolean create) { HttpSession session = request.getSession(create); return session != null ? session.getId() : null; } SpringSecurityRequestAuthenticator( HttpFacade facade, HttpServletRequest request, KeycloakDeployment deployment, AdapterTokenStore tokenStore, int sslRedirectPort); }### Answer: @Test public void testGetHttpSessionIdTrue() throws Exception { String sessionId = authenticator.changeHttpSessionId(true); assertNotNull(sessionId); } @Test public void testGetHttpSessionIdFalse() throws Exception { String sessionId = authenticator.changeHttpSessionId(false); assertNull(sessionId); }
### Question: KeycloakAuthenticationProvider implements AuthenticationProvider { @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { KeycloakAuthenticationToken token = (KeycloakAuthenticationToken) authentication; List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(); for (String role : token.getAccount().getRoles()) { grantedAuthorities.add(new KeycloakRole(role)); } return new KeycloakAuthenticationToken(token.getAccount(), token.isInteractive(), mapAuthorities(grantedAuthorities)); } void setGrantedAuthoritiesMapper(GrantedAuthoritiesMapper grantedAuthoritiesMapper); @Override Authentication authenticate(Authentication authentication); @Override boolean supports(Class<?> aClass); }### Answer: @Test public void testAuthenticate() throws Exception { assertAuthenticationResult(provider.authenticate(token)); } @Test public void testAuthenticateInteractive() throws Exception { assertAuthenticationResult(provider.authenticate(interactiveToken)); }
### Question: KeycloakAuthenticationProvider implements AuthenticationProvider { @Override public boolean supports(Class<?> aClass) { return KeycloakAuthenticationToken.class.isAssignableFrom(aClass); } void setGrantedAuthoritiesMapper(GrantedAuthoritiesMapper grantedAuthoritiesMapper); @Override Authentication authenticate(Authentication authentication); @Override boolean supports(Class<?> aClass); }### Answer: @Test public void testSupports() throws Exception { assertTrue(provider.supports(KeycloakAuthenticationToken.class)); assertFalse(provider.supports(PreAuthenticatedAuthenticationToken.class)); }
### Question: KeycloakLogoutHandler implements LogoutHandler { @Override public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { if (authentication == null) { log.warn("Cannot log out without authentication"); return; } else if (!KeycloakAuthenticationToken.class.isAssignableFrom(authentication.getClass())) { log.warn("Cannot log out a non-Keycloak authentication: {}", authentication); return; } handleSingleSignOut(request, response, (KeycloakAuthenticationToken) authentication); } KeycloakLogoutHandler(AdapterDeploymentContext adapterDeploymentContext); void setAdapterTokenStoreFactory(AdapterTokenStoreFactory adapterTokenStoreFactory); @Override void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication); }### Answer: @Test public void testLogout() throws Exception { keycloakLogoutHandler.logout(request, response, keycloakAuthenticationToken); verify(session).logout(eq(keycloakDeployment)); } @Test public void testLogoutAnonymousAuthentication() throws Exception { Authentication authentication = new AnonymousAuthenticationToken(UUID.randomUUID().toString(), UUID.randomUUID().toString(), authorities); keycloakLogoutHandler.logout(request, response, authentication); verifyZeroInteractions(session); } @Test public void testLogoutUsernamePasswordAuthentication() throws Exception { Authentication authentication = new UsernamePasswordAuthenticationToken(UUID.randomUUID().toString(), UUID.randomUUID().toString(), authorities); keycloakLogoutHandler.logout(request, response, authentication); verifyZeroInteractions(session); } @Test public void testLogoutRememberMeAuthentication() throws Exception { Authentication authentication = new RememberMeAuthenticationToken(UUID.randomUUID().toString(), UUID.randomUUID().toString(), authorities); keycloakLogoutHandler.logout(request, response, authentication); verifyZeroInteractions(session); } @Test public void testLogoutNullAuthentication() throws Exception { keycloakLogoutHandler.logout(request, response, null); verifyZeroInteractions(session); }
### Question: KeycloakLogoutHandler implements LogoutHandler { protected void handleSingleSignOut(HttpServletRequest request, HttpServletResponse response, KeycloakAuthenticationToken authenticationToken) { HttpFacade facade = new SimpleHttpFacade(request, response); KeycloakDeployment deployment = adapterDeploymentContext.resolveDeployment(facade); adapterTokenStoreFactory.createAdapterTokenStore(deployment, request, response).logout(); RefreshableKeycloakSecurityContext session = (RefreshableKeycloakSecurityContext) authenticationToken.getAccount().getKeycloakSecurityContext(); session.logout(deployment); } KeycloakLogoutHandler(AdapterDeploymentContext adapterDeploymentContext); void setAdapterTokenStoreFactory(AdapterTokenStoreFactory adapterTokenStoreFactory); @Override void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication); }### Answer: @Test public void testHandleSingleSignOut() throws Exception { keycloakLogoutHandler.handleSingleSignOut(request, response, keycloakAuthenticationToken); verify(session).logout(eq(keycloakDeployment)); }
### Question: KeycloakAuthenticationEntryPoint implements AuthenticationEntryPoint { public void setLoginUri(String loginUri) { Assert.notNull(loginUri, "loginUri cannot be null"); this.loginUri = loginUri; } KeycloakAuthenticationEntryPoint(AdapterDeploymentContext adapterDeploymentContext); KeycloakAuthenticationEntryPoint(AdapterDeploymentContext adapterDeploymentContext, RequestMatcher apiRequestMatcher); @Override void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException); void setLoginUri(String loginUri); void setRealm(String realm); static final String DEFAULT_LOGIN_URI; }### Answer: @Test public void testSetLoginUri() throws Exception { configureBrowserRequest(); final String logoutUri = "/foo"; authenticationEntryPoint.setLoginUri(logoutUri); authenticationEntryPoint.commence(request, response, null); assertEquals(HttpStatus.FOUND.value(), response.getStatus()); assertEquals(logoutUri, response.getHeader("Location")); }
### 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: 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: 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: 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: 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 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 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: 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: 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: 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: 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: 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 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: 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()); }