method2testcases
stringlengths
118
3.08k
### Question: HttpServerRequestImpl implements HttpServerRequest { @Override public HttpServerRequest customFrameHandler(Handler<HttpFrame> handler) { return this; } HttpServerRequestImpl(String localHost, int localPort, JsonObject request, HttpServerResponse response); @Override HttpServerRequest exceptionHandler(Handler<Throwable> handler); @Override HttpServerRequest handler(Handler<Buffer> dataHandler); @Override HttpServerRequest pause(); @Override HttpServerRequest resume(); @Override HttpServerRequest endHandler(Handler<Void> endHandler); @Override HttpVersion version(); @Override HttpMethod method(); @Override String rawMethod(); @Override boolean isSSL(); @Override String scheme(); @Override String uri(); @Override String path(); @Override String query(); @Override String host(); @Override HttpServerResponse response(); @Override MultiMap headers(); @Override String getHeader(String headerName); @Override String getHeader(CharSequence headerName); @Override MultiMap params(); @Override String getParam(String paramName); @Override SocketAddress remoteAddress(); @Override SocketAddress localAddress(); @Override X509Certificate[] peerCertificateChain(); @Override String absoluteURI(); @Override NetSocket netSocket(); @Override HttpServerRequest setExpectMultipart(boolean expect); @Override boolean isExpectMultipart(); @Override HttpServerRequest uploadHandler(Handler<HttpServerFileUpload> uploadHandler); @Override MultiMap formAttributes(); @Override String getFormAttribute(String attributeName); @Override ServerWebSocket upgrade(); @Override boolean isEnded(); @Override HttpServerRequest customFrameHandler(Handler<HttpFrame> handler); @Override HttpConnection connection(); void handleData(); void handleEnd(); }### Answer: @Test public void testCustomFrameHandler(TestContext context) { context.assertEquals(request, request.customFrameHandler(ar -> { })); }
### Question: HttpServerRequestImpl implements HttpServerRequest { @Override public HttpConnection connection() { return null; } HttpServerRequestImpl(String localHost, int localPort, JsonObject request, HttpServerResponse response); @Override HttpServerRequest exceptionHandler(Handler<Throwable> handler); @Override HttpServerRequest handler(Handler<Buffer> dataHandler); @Override HttpServerRequest pause(); @Override HttpServerRequest resume(); @Override HttpServerRequest endHandler(Handler<Void> endHandler); @Override HttpVersion version(); @Override HttpMethod method(); @Override String rawMethod(); @Override boolean isSSL(); @Override String scheme(); @Override String uri(); @Override String path(); @Override String query(); @Override String host(); @Override HttpServerResponse response(); @Override MultiMap headers(); @Override String getHeader(String headerName); @Override String getHeader(CharSequence headerName); @Override MultiMap params(); @Override String getParam(String paramName); @Override SocketAddress remoteAddress(); @Override SocketAddress localAddress(); @Override X509Certificate[] peerCertificateChain(); @Override String absoluteURI(); @Override NetSocket netSocket(); @Override HttpServerRequest setExpectMultipart(boolean expect); @Override boolean isExpectMultipart(); @Override HttpServerRequest uploadHandler(Handler<HttpServerFileUpload> uploadHandler); @Override MultiMap formAttributes(); @Override String getFormAttribute(String attributeName); @Override ServerWebSocket upgrade(); @Override boolean isEnded(); @Override HttpServerRequest customFrameHandler(Handler<HttpFrame> handler); @Override HttpConnection connection(); void handleData(); void handleEnd(); }### Answer: @Test public void testConnection(TestContext context) { context.assertNull(request.connection()); }
### Question: LambdaServer implements HttpServer { @Override public HttpServer listen() { processRequest(); return this; } LambdaServer(Vertx vertx, Context context, InputStream input, OutputStream output); @Override boolean isMetricsEnabled(); @Override ReadStream<HttpServerRequest> requestStream(); @Override HttpServer requestHandler(Handler<HttpServerRequest> handler); @Override Handler<HttpServerRequest> requestHandler(); @Override HttpServer connectionHandler(Handler<HttpConnection> handler); @Override ReadStream<ServerWebSocket> websocketStream(); @Override HttpServer websocketHandler(Handler<ServerWebSocket> handler); @Override Handler<ServerWebSocket> websocketHandler(); @Override HttpServer listen(); @Override HttpServer listen(int port, String host); @Override HttpServer listen(int port, String host, Handler<AsyncResult<HttpServer>> listenHandler); @Override HttpServer listen(int port); @Override HttpServer listen(int port, Handler<AsyncResult<HttpServer>> listenHandler); @Override HttpServer listen(Handler<AsyncResult<HttpServer>> listenHandler); @Override void close(); @Override void close(Handler<AsyncResult<Void>> completionHandler); @Override int actualPort(); }### Answer: @Test public void testListen(TestContext context) { server.requestHandler(req -> { context.assertEquals("0.0.0.0", req.host()); req.response().end("data"); }); context.assertEquals(server, server.listen()); context.assertEquals(0, server.actualPort()); JsonObject response = new JsonObject(outputData.toString()); context.assertEquals("4", response.getJsonObject("headers").getString("Content-Length")); context.assertEquals(200, response.getInteger("statusCode")); context.assertTrue(response.getBoolean("isBase64Encoded")); context.assertEquals("data", new String(response.getBinary("body"))); }
### Question: LambdaServer implements HttpServer { @Override public void close() { } LambdaServer(Vertx vertx, Context context, InputStream input, OutputStream output); @Override boolean isMetricsEnabled(); @Override ReadStream<HttpServerRequest> requestStream(); @Override HttpServer requestHandler(Handler<HttpServerRequest> handler); @Override Handler<HttpServerRequest> requestHandler(); @Override HttpServer connectionHandler(Handler<HttpConnection> handler); @Override ReadStream<ServerWebSocket> websocketStream(); @Override HttpServer websocketHandler(Handler<ServerWebSocket> handler); @Override Handler<ServerWebSocket> websocketHandler(); @Override HttpServer listen(); @Override HttpServer listen(int port, String host); @Override HttpServer listen(int port, String host, Handler<AsyncResult<HttpServer>> listenHandler); @Override HttpServer listen(int port); @Override HttpServer listen(int port, Handler<AsyncResult<HttpServer>> listenHandler); @Override HttpServer listen(Handler<AsyncResult<HttpServer>> listenHandler); @Override void close(); @Override void close(Handler<AsyncResult<Void>> completionHandler); @Override int actualPort(); }### Answer: @Test public void testClose(TestContext context) { server.close(); } @Test public void testClose2(TestContext context) { Future<Void> future = Future.future(); server.close(future); context.assertTrue(future.succeeded()); }
### Question: CommonUtils { public static Boolean isAscendingOrder(String sorting) { return "desc".equalsIgnoreCase(sorting) ? Boolean.FALSE : Boolean.TRUE; } private CommonUtils(); static Boolean isAscendingOrder(String sorting); static String removeDefaultHttpPorts(final String uri); }### Answer: @Test public void verifyAscendingOrderFromNullValue() { assertThat(isAscendingOrder(null)).isTrue(); } @Test public void verfiyAscendingOrderFromDescValue() { assertThat(isAscendingOrder("deSc")).isFalse(); assertThat(isAscendingOrder("desc")).isFalse(); assertThat(isAscendingOrder("DESC")).isFalse(); } @Test public void verifyAscendingOrderFromAscValue() { assertThat(isAscendingOrder("foo")).isTrue(); assertThat(isAscendingOrder("AsC")).isTrue(); }
### Question: CommonUtils { public static String removeDefaultHttpPorts(final String uri) { URL url; try { url = new URL(uri); if (url.getPort() == url.getDefaultPort()) { String urlPort = ":" + url.getPort(); return url.toExternalForm().replace(urlPort, ""); } } catch (MalformedURLException e) { return null; } return url.toExternalForm(); } private CommonUtils(); static Boolean isAscendingOrder(String sorting); static String removeDefaultHttpPorts(final String uri); }### Answer: @Test public void httpsPorts() { assertThat(removeDefaultHttpPorts("https: assertThat(removeDefaultHttpPorts("https: assertThat(removeDefaultHttpPorts("https: assertThat(removeDefaultHttpPorts("localhost/auth")).isNull(); } @Test public void httpPorts() { assertThat(removeDefaultHttpPorts("http: assertThat(removeDefaultHttpPorts("http: assertThat(removeDefaultHttpPorts("http: assertThat(removeDefaultHttpPorts("localhost/auth")).isNull(); }
### Question: iOSApplicationUploadForm { @AssertTrue(message = "the provided certificate passphrase does not match with the uploaded certificate") public boolean isCertificatePassphraseValid() { try { PKCS12.validate(certificate, passphrase); return true; } catch (Exception e) { return false; } } iOSApplicationUploadForm(); Boolean getProduction(); @FormParam("production") void setProduction(Boolean production); String getName(); @FormParam("variantID") void setVariantID(String variantID); @FormParam("secret") void setSecret(String secret); String getSecret(); String getVariantID(); @FormParam("name") void setName(String name); String getDescription(); @FormParam("description") void setDescription(String description); String getPassphrase(); @FormParam("passphrase") void setPassphrase(String passphrase); byte[] getCertificate(); @FormParam("certificate") @PartType("application/octet-stream") void setCertificate(byte[] data); @AssertTrue(message = "the provided certificate passphrase does not match with the uploaded certificate") boolean isCertificatePassphraseValid(); void apply(iOSVariant iOSVariant); }### Answer: @Test public void testIsCertificatePassPhraseValid() throws Exception { iOSApplicationUploadForm form = new iOSApplicationUploadForm(); form.setCertificate(IOUtils.toByteArray(getClass().getResourceAsStream("/Certificates.p12"))); form.setPassphrase("aero1gears"); final Set<ConstraintViolation<iOSApplicationUploadForm>> constraintViolations = validator.validate(form); assertThat(constraintViolations).isEmpty(); }
### Question: AndroidVariantEndpoint extends AbstractVariantEndpoint<AndroidVariant> { @GET @Produces(MediaType.APPLICATION_JSON) public Response listAllAndroidVariationsForPushApp(@PathParam("pushAppID") String pushApplicationID) { final PushApplication application = getSearch().findByPushApplicationIDForDeveloper(pushApplicationID); if (application == null) { return Response.status(Response.Status.NOT_FOUND).entity(ErrorBuilder.forPushApplications().notFound().build()).build(); } return Response.ok(getVariants(application)).build(); } AndroidVariantEndpoint(); AndroidVariantEndpoint(Validator validator, SearchManager searchManager); @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) Response registerAndroidVariant( AndroidVariant androidVariant, @PathParam("pushAppID") String pushApplicationID, @Context UriInfo uriInfo); @GET @Produces(MediaType.APPLICATION_JSON) Response listAllAndroidVariationsForPushApp(@PathParam("pushAppID") String pushApplicationID); @PUT @Path("/{androidID}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) Response updateAndroidVariant( @PathParam("pushAppID") String pushApplicationId, @PathParam("androidID") String androidID, AndroidVariant updatedAndroidApplication); }### Answer: @Test public void shouldListAllAndroidVariationsForPushAppSuccessfully() { final Variant androidVariant = new AndroidVariant(); final Variant iOSVariant = new iOSVariant(); final PushApplication pushApp = new PushApplication(); pushApp.setVariants(Lists.newArrayList(androidVariant, iOSVariant)); when(searchService.findByPushApplicationIDForDeveloper("push-app-id")).thenReturn(pushApp); final Response response = this.endpoint.listAllAndroidVariationsForPushApp("push-app-id"); assertEquals(response.getStatus(), 200); assertTrue(((Collection) response.getEntity()).iterator().next() == androidVariant); }
### Question: ConfigurationUtils { public static String tryGetGlobalProperty(String key, String defaultValue) { try { String value = System.getenv(formatEnvironmentVariable(key)); if (value == null) { value = tryGetProperty(key, defaultValue); } return value; } catch (SecurityException e) { logger.error("Could not get value of global property {} due to SecurityManager. Using default value.", key, e); return defaultValue; } } private ConfigurationUtils(); static String formatEnvironmentVariable(String key); static String tryGetGlobalProperty(String key, String defaultValue); static String tryGetGlobalProperty(String key); static Integer tryGetGlobalIntegerProperty(String key, Integer defaultValue); static Integer tryGetGlobalIntegerProperty(String key); }### Answer: @Test public void testExistingTryGetProperty(){ System.setProperty(TEST_PROPERTY_NAME, "MyNiceValue"); assertThat(ConfigurationUtils.tryGetGlobalProperty(TEST_PROPERTY_NAME)).isEqualTo("MyNiceValue"); } @Test public void testNonExistingTryGetProperty(){ assertThat(ConfigurationUtils.tryGetGlobalProperty(TEST_PROPERTY_NAME)).isNull(); } @Test public void testEnvVarLookup() { assertThat(ConfigurationUtils.tryGetGlobalProperty("test.env.var")) .isEqualTo("Ok"); } @Test public void testEnvVarUppercaseLookup() { assertThat(ConfigurationUtils.tryGetGlobalProperty("TEST_ENV_VAR")) .isEqualTo("Ok"); }
### Question: ConfigurationUtils { public static Integer tryGetGlobalIntegerProperty(String key, Integer defaultValue) { try { String value = System.getenv(formatEnvironmentVariable(key)); if (value == null) { return tryGetIntegerProperty(key, defaultValue); } else { return Integer.parseInt(value); } } catch (SecurityException | NumberFormatException e) { logger.error("Could not get value of global property {} due to SecurityManager. Using default value.", key, e); return defaultValue; } } private ConfigurationUtils(); static String formatEnvironmentVariable(String key); static String tryGetGlobalProperty(String key, String defaultValue); static String tryGetGlobalProperty(String key); static Integer tryGetGlobalIntegerProperty(String key, Integer defaultValue); static Integer tryGetGlobalIntegerProperty(String key); }### Answer: @Test public void testExistingTryGetIntegerProperty() { System.setProperty(TEST_PROPERTY_NAME, "123456"); assertThat(ConfigurationUtils.tryGetGlobalIntegerProperty(TEST_PROPERTY_NAME)).isEqualTo(123456); } @Test public void testNonExistingTryGetIntegerProperty() { assertThat(ConfigurationUtils.tryGetGlobalIntegerProperty(TEST_PROPERTY_NAME)).isNull(); } @Test public void testNonExistingTryGetIntegerPropertyWithDefaultValue() { assertThat(ConfigurationUtils.tryGetGlobalIntegerProperty(TEST_PROPERTY_NAME, 123)).isEqualTo(123); }
### Question: ConfigurationUtils { public static String formatEnvironmentVariable(String key) { return key.toUpperCase().replaceAll("\\.", "_"); } private ConfigurationUtils(); static String formatEnvironmentVariable(String key); static String tryGetGlobalProperty(String key, String defaultValue); static String tryGetGlobalProperty(String key); static Integer tryGetGlobalIntegerProperty(String key, Integer defaultValue); static Integer tryGetGlobalIntegerProperty(String key); }### Answer: @Test public void testEnvVarFormat() { assertThat(ConfigurationUtils.formatEnvironmentVariable("custom.aerogear.apns.push.host")) .isEqualTo("CUSTOM_AEROGEAR_APNS_PUSH_HOST"); }
### Question: SenderConfigurationProvider { @Produces @ApplicationScoped @SenderType(VariantType.ANDROID) public SenderConfiguration produceAndroidConfiguration() { return loadConfigurationFor(VariantType.ANDROID, new SenderConfiguration(10, 1000)); } @Produces @ApplicationScoped @SenderType(VariantType.ANDROID) SenderConfiguration produceAndroidConfiguration(); @Produces @ApplicationScoped @SenderType(VariantType.IOS) SenderConfiguration produceIosConfiguration(); @Produces @ApplicationScoped @SenderType(VariantType.IOS_TOKEN) SenderConfiguration produceIosTokenConfiguration(); @Produces @ApplicationScoped @SenderType(VariantType.WEB_PUSH) SenderConfiguration produceWebPushConfiguration(); }### Answer: @Test public void testAndroidConfigurationSanitization() { try { System.setProperty("aerogear.android.batchSize", "1005"); SenderConfiguration configuration = provider.produceAndroidConfiguration(); assertEquals(10, configuration.batchesToLoad()); assertEquals(1000, configuration.batchSize()); } finally { System.clearProperty("aerogear.android.batchSize"); } }
### Question: TokenLoaderUtils { public static boolean isEmptyCriteria(final Criteria criteria) { return isEmpty(criteria.getAliases()) && isEmpty(criteria.getDeviceTypes()) && isEmpty(criteria.getCategories()); } private TokenLoaderUtils(); static Set<String> extractFCMTopics(final Criteria criteria, final String variantID); static boolean isCategoryOnlyCriteria(final Criteria criteria); static boolean isEmptyCriteria(final Criteria criteria); static boolean isFCMTopicRequest(final Criteria criteria); }### Answer: @Test public void testEmptyCriteria() { final Criteria criteria = new Criteria(); assertThat(TokenLoaderUtils.isEmptyCriteria(criteria)).isTrue(); } @Test public void testNonEmptyCriteria() { final Criteria criteria = new Criteria(); criteria.setAliases(Arrays.asList("foo", "bar")); assertThat(TokenLoaderUtils.isEmptyCriteria(criteria)).isFalse(); }
### Question: TokenLoaderUtils { public static boolean isCategoryOnlyCriteria(final Criteria criteria) { return isEmpty(criteria.getAliases()) && isEmpty(criteria.getDeviceTypes()) && !isEmpty(criteria.getCategories()); } private TokenLoaderUtils(); static Set<String> extractFCMTopics(final Criteria criteria, final String variantID); static boolean isCategoryOnlyCriteria(final Criteria criteria); static boolean isEmptyCriteria(final Criteria criteria); static boolean isFCMTopicRequest(final Criteria criteria); }### Answer: @Test public void testNotCategoryOnly() { final Criteria criteria = new Criteria(); criteria.setAliases(Arrays.asList("foo", "bar")); assertThat(TokenLoaderUtils.isCategoryOnlyCriteria(criteria)).isFalse(); } @Test public void testCategoryOnly() { final Criteria criteria = new Criteria(); criteria.setCategories(Arrays.asList("football")); assertThat(TokenLoaderUtils.isCategoryOnlyCriteria(criteria)).isTrue(); } @Test public void testNotCategoryOnlyForEmpyt() { final Criteria criteria = new Criteria(); assertThat(TokenLoaderUtils.isCategoryOnlyCriteria(criteria)).isFalse(); }
### Question: TokenLoaderUtils { public static Set<String> extractFCMTopics(final Criteria criteria, final String variantID) { final Set<String> topics = new TreeSet<>(); if (isEmptyCriteria(criteria)) { topics.add(Constants.TOPIC_PREFIX + variantID); } else if (isCategoryOnlyCriteria(criteria)) { topics.addAll(criteria.getCategories().stream() .map(category -> Constants.TOPIC_PREFIX + category) .collect(Collectors.toList())); } return topics; } private TokenLoaderUtils(); static Set<String> extractFCMTopics(final Criteria criteria, final String variantID); static boolean isCategoryOnlyCriteria(final Criteria criteria); static boolean isEmptyCriteria(final Criteria criteria); static boolean isFCMTopicRequest(final Criteria criteria); }### Answer: @Test public void testGcmTopicExtractionForEmptyCriteria() { final Criteria criteria = new Criteria(); assertThat(TokenLoaderUtils.extractFCMTopics(criteria, "123")).isNotEmpty(); assertThat(TokenLoaderUtils.extractFCMTopics(criteria, "123")).containsOnly( Constants.TOPIC_PREFIX+"123" ); }
### Question: TokenLoaderUtils { public static boolean isFCMTopicRequest(final Criteria criteria) { return isEmptyCriteria(criteria) || isCategoryOnlyCriteria(criteria); } private TokenLoaderUtils(); static Set<String> extractFCMTopics(final Criteria criteria, final String variantID); static boolean isCategoryOnlyCriteria(final Criteria criteria); static boolean isEmptyCriteria(final Criteria criteria); static boolean isFCMTopicRequest(final Criteria criteria); }### Answer: @Test public void testGCMTopicForAlias() { final Criteria criteria = new Criteria(); criteria.setAliases(Arrays.asList("[email protected]")); assertThat(TokenLoaderUtils.isFCMTopicRequest(criteria)).isFalse(); } @Test public void testGCMTopicForVariant() { final Criteria criteria = new Criteria(); criteria.setVariants(Arrays.asList("variant1", "variant2")); assertThat(TokenLoaderUtils.isFCMTopicRequest(criteria)).isTrue(); } @Test public void testGCMTopicForVariantAndAlias() { final Criteria criteria = new Criteria(); criteria.setVariants(Arrays.asList("variant1", "variant2")); criteria.setAliases(Arrays.asList("[email protected]")); assertThat(TokenLoaderUtils.isFCMTopicRequest(criteria)).isFalse(); }
### Question: LoginController { public String login(UserForm userForm) { System.out.println("LoginController.login " + userForm); try { if (userForm == null) { return "ERROR"; } else if (loginService.login(userForm)) { return "OK"; } else { return "KO"; } } catch (Exception e) { return "ERROR"; } } String login(UserForm userForm); void logout(UserForm userForm); public LoginService loginService; }### Answer: @Test public void testLogin() { loginController.login(userForm); verify(loginService).login(userForm); verifyNoMoreInteractions(loginService); } @Test public void testLoginOk() { when(loginService.login(userForm)).thenReturn(true); assertEquals("OK", loginController.login(userForm)); verify(loginService).login(userForm); verifyNoMoreInteractions(loginService); } @Test public void testLoginKo() { when(loginService.login(userForm)).thenReturn(false); assertEquals("KO", loginController.login(userForm)); } @Test public void testLoginError() { assertEquals("ERROR", loginController.login(null)); } @Test public void testLoginWithException() { when(loginService.login(userForm)) .thenThrow(IllegalArgumentException.class); assertEquals("ERROR", loginController.login(userForm)); }
### Question: LoginService { public boolean login(UserForm userForm) { System.out.println("LoginService.login " + userForm); checkForm(userForm); String username = userForm.getUsername(); if (usersLogged.contains(username)) { throw new LoginException(username + " already logged"); } boolean login = loginRepository.login(userForm); if (login) { usersLogged.add(username); } return login; } boolean login(UserForm userForm); void logout(UserForm userForm); int getUserLoggedCount(); }### Answer: @Test void testLoginKo() { when(loginRepository.login(any(UserForm.class))).thenReturn(false); assertFalse(loginService.login(userForm)); verify(loginRepository, times(1)).login(userForm); } @Test void testLoginTwice() { when(loginRepository.login(userForm)).thenReturn(true); assertThrows(LoginException.class, () -> { loginService.login(userForm); loginService.login(userForm); }); } @Test public void testServiceLoginOk() { when(loginRepository.login(any(UserForm.class))).thenReturn(true); assertTrue(loginService.login(userForm)); verify(loginRepository, atLeast(1)).login(userForm); verifyNoMoreInteractions(loginRepository); } @Test public void testServiceLoginBad() { when(loginRepository.login(any(UserForm.class))).thenReturn(false); assertFalse(loginService.login(userForm)); verify(loginRepository, times(1)).login(userForm); verifyNoMoreInteractions(loginRepository); } @Test(expected = LoginException.class) public void testServiceLoginTwice() { when(loginRepository.login(userForm)).thenReturn(true); loginService.login(userForm); loginService.login(userForm); } @Test void testLoginOk() { when(loginRepository.login(any(UserForm.class))).thenReturn(true); assertTrue(loginService.login(userForm)); verify(loginRepository, atLeast(1)).login(userForm); }
### Question: LoginController { public void logout(UserForm userForm) { System.out.println("LoginController.logout " + userForm); loginService.logout(userForm); } String login(UserForm userForm); void logout(UserForm userForm); public LoginService loginService; }### Answer: @Test public void testLogout() { loginController.logout(userForm); verify(loginService).logout(userForm); verifyNoMoreInteractions(loginService); }
### Question: ShuffledMergedInputConfiguration { public static Builder newBuilder(String keyClass, String valueClass) { return new Builder(keyClass, valueClass); } @InterfaceAudience.Private @VisibleForTesting ShuffledMergedInputConfiguration(); private ShuffledMergedInputConfiguration(Configuration conf, boolean useLegacyInput); byte[] toByteArray(); void fromByteArray(byte[] payload); String getInputClassName(); static Builder newBuilder(String keyClass, String valueClass); }### Answer: @Test public void testNullParams() { try { ShuffledMergedInputConfiguration.newBuilder(null, "VALUE"); fail("Expecting a null parameter list to fail"); } catch (NullPointerException npe) { assertTrue(npe.getMessage().contains("cannot be null")); } try { ShuffledMergedInputConfiguration.newBuilder("KEY", null); fail("Expecting a null parameter list to fail"); } catch (NullPointerException npe) { assertTrue(npe.getMessage().contains("cannot be null")); } }
### Question: OnFileUnorderedKVOutputConfiguration { public static Builder newBuilder(String keyClass, String valClass) { return new Builder(keyClass, valClass); } @InterfaceAudience.Private @VisibleForTesting OnFileUnorderedKVOutputConfiguration(); private OnFileUnorderedKVOutputConfiguration(Configuration conf); byte[] toByteArray(); @InterfaceAudience.Private void fromByteArray(byte[] payload); static Builder newBuilder(String keyClass, String valClass); }### Answer: @Test public void testNullParams() { try { OnFileUnorderedKVOutputConfiguration.newBuilder( null, "VALUE"); fail("Expecting a null parameter list to fail"); } catch (NullPointerException npe) { assertTrue(npe.getMessage().contains("cannot be null")); } try { OnFileUnorderedKVOutputConfiguration.newBuilder( "KEY", null); fail("Expecting a null parameter list to fail"); } catch (NullPointerException npe) { assertTrue(npe.getMessage().contains("cannot be null")); } }
### Question: UnorderedUnpartitionedKVEdgeConfigurer extends HadoopKeyValuesBasedBaseConf { public static Builder newBuilder(String keyClassName, String valueClassName) { return new Builder(keyClassName, valueClassName); } private UnorderedUnpartitionedKVEdgeConfigurer( OnFileUnorderedKVOutputConfiguration outputConfiguration, ShuffledUnorderedKVInputConfiguration inputConfiguration); static Builder newBuilder(String keyClassName, String valueClassName); @Override byte[] getOutputPayload(); @Override String getOutputClassName(); @Override byte[] getInputPayload(); @Override String getInputClassName(); EdgeProperty createDefaultBroadcastEdgeProperty(); EdgeProperty createDefaultOneToOneEdgeProperty(); EdgeProperty createDefaultCustomEdgeProperty(EdgeManagerDescriptor edgeManagerDescriptor); }### Answer: @Test public void testNullParams() { try { UnorderedUnpartitionedKVEdgeConfigurer.newBuilder(null, "VALUE"); fail("Expecting a null parameter list to fail"); } catch (NullPointerException npe) { assertTrue(npe.getMessage().contains("cannot be null")); } try { UnorderedUnpartitionedKVEdgeConfigurer.newBuilder("KEY", null); fail("Expecting a null parameter list to fail"); } catch (NullPointerException npe) { assertTrue(npe.getMessage().contains("cannot be null")); } }
### Question: OrderedPartitionedKVEdgeConfigurer extends HadoopKeyValuesBasedBaseConf { public static Builder newBuilder(String keyClassName, String valueClassName, String partitionerClassName, Configuration partitionerConf) { return new Builder(keyClassName, valueClassName, partitionerClassName, partitionerConf); } private OrderedPartitionedKVEdgeConfigurer( OnFileSortedOutputConfiguration outputConfiguration, ShuffledMergedInputConfiguration inputConfiguration); static Builder newBuilder(String keyClassName, String valueClassName, String partitionerClassName, Configuration partitionerConf); @Override byte[] getOutputPayload(); @Override String getOutputClassName(); @Override byte[] getInputPayload(); @Override String getInputClassName(); EdgeProperty createDefaultEdgeProperty(); EdgeProperty createDefaultCustomEdgeProperty(EdgeManagerDescriptor edgeManagerDescriptor); }### Answer: @Test public void testNullParams() { try { OrderedPartitionedKVEdgeConfigurer.newBuilder(null, "VALUE", "PARTITIONER", null); fail("Expecting a null parameter list to fail"); } catch (NullPointerException npe) { assertTrue(npe.getMessage().contains("cannot be null")); } try { OrderedPartitionedKVEdgeConfigurer.newBuilder("KEY", null, "PARTITIONER", null); fail("Expecting a null parameter list to fail"); } catch (NullPointerException npe) { assertTrue(npe.getMessage().contains("cannot be null")); } try { OrderedPartitionedKVEdgeConfigurer.newBuilder("KEY", "VALUE", null, null); fail("Expecting a null parameter list to fail"); } catch (NullPointerException npe) { assertTrue(npe.getMessage().contains("cannot be null")); } }
### Question: OnFileSortedOutputConfiguration { public static Builder newBuilder(String keyClass, String valueClass, String partitionerClassName, Configuration partitionerConf) { return new Builder(keyClass, valueClass, partitionerClassName, partitionerConf); } @InterfaceAudience.Private @VisibleForTesting OnFileSortedOutputConfiguration(); private OnFileSortedOutputConfiguration(Configuration conf); byte[] toByteArray(); @InterfaceAudience.Private void fromByteArray(byte[] payload); static Builder newBuilder(String keyClass, String valueClass, String partitionerClassName, Configuration partitionerConf); }### Answer: @Test public void testNullParams() { try { OnFileSortedOutputConfiguration.newBuilder( null, "VALUE", "PARTITIONER", null); fail("Expecting a null parameter list to fail"); } catch (NullPointerException npe) { assertTrue(npe.getMessage().contains("cannot be null")); } try { OnFileSortedOutputConfiguration.newBuilder( "KEY", null, "PARTITIONER", null); fail("Expecting a null parameter list to fail"); } catch (NullPointerException npe) { assertTrue(npe.getMessage().contains("cannot be null")); } try { OnFileSortedOutputConfiguration.newBuilder( "KEY", "VALUE", null, null); fail("Expecting a null parameter list to fail"); } catch (NullPointerException npe) { assertTrue(npe.getMessage().contains("cannot be null")); } }
### Question: UnorderedPartitionedKVEdgeConfigurer extends HadoopKeyValuesBasedBaseConf { public static Builder newBuilder(String keyClassName, String valueClassName, String partitionerClassName, Configuration partitionerConf) { return new Builder(keyClassName, valueClassName, partitionerClassName, partitionerConf); } private UnorderedPartitionedKVEdgeConfigurer( OnFileUnorderedPartitionedKVOutputConfiguration outputConfiguration, ShuffledUnorderedKVInputConfiguration inputConfiguration); static Builder newBuilder(String keyClassName, String valueClassName, String partitionerClassName, Configuration partitionerConf); @Override byte[] getOutputPayload(); @Override String getOutputClassName(); @Override byte[] getInputPayload(); @Override String getInputClassName(); EdgeProperty createDefaultEdgeProperty(); EdgeProperty createDefaultCustomEdgeProperty(EdgeManagerDescriptor edgeManagerDescriptor); }### Answer: @Test public void testNullParams() { try { UnorderedPartitionedKVEdgeConfigurer.newBuilder(null, "VALUE", "PARTITIONER", null); fail("Expecting a null parameter list to fail"); } catch (NullPointerException npe) { assertTrue(npe.getMessage().contains("cannot be null")); } try { UnorderedPartitionedKVEdgeConfigurer.newBuilder("KEY", null, "PARTITIONER", null); fail("Expecting a null parameter list to fail"); } catch (NullPointerException npe) { assertTrue(npe.getMessage().contains("cannot be null")); } try { UnorderedPartitionedKVEdgeConfigurer.newBuilder("KEY", "VALUE", null, null); fail("Expecting a null parameter list to fail"); } catch (NullPointerException npe) { assertTrue(npe.getMessage().contains("cannot be null")); } }
### Question: ShuffledUnorderedKVInputConfiguration { public static Builder newBuilder(String keyClass, String valueClass) { return new Builder(keyClass, valueClass); } @InterfaceAudience.Private @VisibleForTesting ShuffledUnorderedKVInputConfiguration(); private ShuffledUnorderedKVInputConfiguration(Configuration conf); byte[] toByteArray(); void fromByteArray(byte[] payload); static Builder newBuilder(String keyClass, String valueClass); }### Answer: @Test public void testNullParams() { try { ShuffledUnorderedKVInputConfiguration.newBuilder(null, "VALUE"); fail("Expecting a null parameter list to fail"); } catch (NullPointerException npe) { assertTrue(npe.getMessage().contains("cannot be null")); } try { ShuffledUnorderedKVInputConfiguration.newBuilder("KEY", null); fail("Expecting a null parameter list to fail"); } catch (NullPointerException npe) { assertTrue(npe.getMessage().contains("cannot be null")); } }
### Question: TezUtils { @Private public static String cleanVertexName(String vertexName) { return sanitizeString(vertexName).substring(0, vertexName.length() > MAX_VERTEX_NAME_LENGTH ? MAX_VERTEX_NAME_LENGTH : vertexName.length()); } static void addUserSpecifiedTezConfiguration(Configuration conf); static ByteString createByteStringFromConf(Configuration conf); static byte[] createUserPayloadFromConf(Configuration conf); static Configuration createConfFromByteString(ByteString byteString); static Configuration createConfFromUserPayload(byte[] bb); static byte[] compressBytes(byte[] inBytes); static byte[] uncompressBytes(byte[] inBytes); @Private static String cleanVertexName(String vertexName); static void updateLoggers(String addend); static BitSet fromByteArray(byte[] bytes); static byte[] toByteArray(BitSet bits); static String getContainerLogDir(); @Private static final int MAX_VERTEX_NAME_LENGTH; }### Answer: @Test public void testCleanVertexName() { String testString = "special characters & spaces and longer than " + TezUtils.MAX_VERTEX_NAME_LENGTH + " characters"; Assert.assertTrue(testString.length() > TezUtils.MAX_VERTEX_NAME_LENGTH); String cleaned = TezUtils.cleanVertexName(testString); Assert.assertTrue(cleaned.length() <= TezUtils.MAX_VERTEX_NAME_LENGTH); Assert.assertFalse(cleaned.contains("\\s+")); Assert.assertTrue(cleaned.matches("\\w+")); }
### Question: TezUtils { public static byte[] toByteArray(BitSet bits) { if (bits == null) { return null; } byte[] bytes = new byte[bits.length() / 8 + 1]; for (int i = 0; i < bits.length(); i++) { if (bits.get(i)) { bytes[(bytes.length) - (i / 8) - 1] |= 1 << (i % 8); } } return bytes; } static void addUserSpecifiedTezConfiguration(Configuration conf); static ByteString createByteStringFromConf(Configuration conf); static byte[] createUserPayloadFromConf(Configuration conf); static Configuration createConfFromByteString(ByteString byteString); static Configuration createConfFromUserPayload(byte[] bb); static byte[] compressBytes(byte[] inBytes); static byte[] uncompressBytes(byte[] inBytes); @Private static String cleanVertexName(String vertexName); static void updateLoggers(String addend); static BitSet fromByteArray(byte[] bytes); static byte[] toByteArray(BitSet bits); static String getContainerLogDir(); @Private static final int MAX_VERTEX_NAME_LENGTH; }### Answer: @Test public void testBitSetToByteArray() { BitSet bitSet = createBitSet(0); byte[] bytes = TezUtils.toByteArray(bitSet); Assert.assertTrue(bytes.length == ((bitSet.length() / 8) + 1)); bitSet = createBitSet(1000); bytes = TezUtils.toByteArray(bitSet); Assert.assertTrue(bytes.length == ((bitSet.length() / 8) + 1)); }
### Question: TezClientUtils { static void maybeAddDefaultLoggingJavaOpts(String logLevel, List<String> vargs) { if (vargs != null && !vargs.isEmpty()) { for (String arg : vargs) { if (arg.contains(TezConfiguration.TEZ_ROOT_LOGGER_NAME)) { return ; } } } TezClientUtils.addLog4jSystemProperties(logLevel, vargs); } static FileSystem ensureStagingDirExists(Configuration conf, Path stagingArea); @Private @VisibleForTesting static void addLog4jSystemProperties(String logLevel, List<String> vargs); @Private static DAGClientAMProtocolBlockingPB getAMProxy(final Configuration conf, String amHost, int amRpcPort, org.apache.hadoop.yarn.api.records.Token clientToAMToken); @Private static void createSessionToken(String tokenIdentifier, JobTokenSecretManager jobTokenSecretManager, Credentials credentials); static String maybeAddDefaultMemoryJavaOpts(String javaOpts, Resource resource, double maxHeapFactor); }### Answer: @Test (timeout=5000) public void testDefaultLoggingJavaOpts() { String origJavaOpts = null; String javaOpts = TezClientUtils.maybeAddDefaultLoggingJavaOpts("FOOBAR", origJavaOpts); Assert.assertNotNull(javaOpts); Assert.assertTrue(javaOpts.contains("-D" + TezConfiguration.TEZ_ROOT_LOGGER_NAME + "=FOOBAR") && javaOpts.contains(TezConfiguration.TEZ_CONTAINER_LOG4J_PROPERTIES_FILE)); }
### Question: AMNodeMap extends AbstractService implements EventHandler<AMNodeEvent> { public void handle(AMNodeEvent rEvent) { NodeId nodeId = rEvent.getNodeId(); switch (rEvent.getType()) { case N_NODE_WAS_BLACKLISTED: addToBlackList(nodeId); computeIgnoreBlacklisting(); break; case N_NODE_COUNT_UPDATED: AMNodeEventNodeCountUpdated event = (AMNodeEventNodeCountUpdated) rEvent; numClusterNodes = event.getNodeCount(); LOG.info("Num cluster nodes = " + numClusterNodes); computeIgnoreBlacklisting(); break; case N_TURNED_UNHEALTHY: case N_TURNED_HEALTHY: AMNode amNode = nodeMap.get(nodeId); if (amNode == null) { LOG.info("Ignoring RM Health Update for unknwon node: " + nodeId); } else { amNode.handle(rEvent); } break; default: nodeMap.get(nodeId).handle(rEvent); } } @SuppressWarnings("rawtypes") AMNodeMap(EventHandler eventHandler, AppContext appContext); @Override synchronized void serviceInit(Configuration conf); void nodeSeen(NodeId nodeId); boolean isHostBlackListed(String hostname); void handle(AMNodeEvent rEvent); AMNode get(NodeId nodeId); int size(); @Private @VisibleForTesting boolean isBlacklistingIgnored(); }### Answer: @Test(timeout=5000) public void testHealthUpdateUnknownNode() { AppContext appContext = mock(AppContext.class); AMNodeMap amNodeMap = new AMNodeMap(eventHandler, appContext); amNodeMap.init(new Configuration(false)); amNodeMap.start(); NodeId nodeId = NodeId.newInstance("unknownhost", 2342); NodeReport nodeReport = generateNodeReport(nodeId, NodeState.UNHEALTHY); amNodeMap.handle(new AMNodeEventStateChanged(nodeReport)); dispatcher.await(); amNodeMap.stop(); }
### Question: VertexStatusBuilder extends VertexStatus { @VisibleForTesting static VertexStatusStateProto getProtoState(VertexState state) { switch(state) { case NEW: return VertexStatusStateProto.VERTEX_NEW; case INITIALIZING: return VertexStatusStateProto.VERTEX_INITIALIZING; case RECOVERING: return VertexStatusStateProto.VERTEX_NEW; case INITED: return VertexStatusStateProto.VERTEX_INITED; case RUNNING: return VertexStatusStateProto.VERTEX_RUNNING; case SUCCEEDED: return VertexStatusStateProto.VERTEX_SUCCEEDED; case FAILED: return VertexStatusStateProto.VERTEX_FAILED; case KILLED: return VertexStatusStateProto.VERTEX_KILLED; case TERMINATING: return VertexStatusStateProto.VERTEX_TERMINATING; case ERROR: return VertexStatusStateProto.VERTEX_ERROR; default: throw new TezUncheckedException("Unsupported value for VertexState : " + state); } } VertexStatusBuilder(); void setState(VertexState state); void setDiagnostics(List<String> diagnostics); void setProgress(ProgressBuilder progress); void setVertexCounters(TezCounters counters); VertexStatusProto getProto(); }### Answer: @Test public void testVertexStateConversion() { for (VertexState state : VertexState.values()) { DAGProtos.VertexStatusStateProto stateProto = VertexStatusBuilder.getProtoState(state); VertexStatus.State clientState = VertexStatus.getState(stateProto); if (state.equals(VertexState.RECOVERING)) { Assert.assertEquals(clientState.name(), State.NEW.name()); } else { Assert.assertEquals(state.name(), clientState.name()); } } }
### Question: EnvironmentUpdateUtils { public static void put(String key, String value){ Map<String, String> environment = new HashMap<String, String>(System.getenv()); environment.put(key, value); updateEnvironment(environment); } static void put(String key, String value); static void putAll(Map<String, String> additionalEnvironment); }### Answer: @Test public void testMultipleUpdateEnvironment() { EnvironmentUpdateUtils.put("test.environment1", "test.value1"); EnvironmentUpdateUtils.put("test.environment2", "test.value2"); assertEquals("Environment was not set propertly", "test.value1", System.getenv("test.environment1")); assertEquals("Environment was not set propertly", "test.value2", System.getenv("test.environment2")); }
### Question: ATSHistoryLoggingService extends HistoryLoggingService { public void handle(DAGHistoryEvent event) { eventQueue.add(event); } ATSHistoryLoggingService(); @Override void serviceInit(Configuration conf); @Override void serviceStart(); @Override void serviceStop(); void handle(DAGHistoryEvent event); }### Answer: @Test(timeout=20000) public void testATSHistoryLoggingServiceShutdown() { TezDAGID tezDAGID = TezDAGID.getInstance( ApplicationId.newInstance(100l, 1), 1); DAGHistoryEvent historyEvent = new DAGHistoryEvent(tezDAGID, new DAGStartedEvent(tezDAGID, 1001l, "user1", "dagName1")); for (int i = 0; i < 20; ++i) { atsHistoryLoggingService.handle(historyEvent); } try { Thread.sleep(2500l); } catch (InterruptedException e) { } atsHistoryLoggingService.stop(); Assert.assertTrue(atsInvokeCounter >= 4); Assert.assertTrue(atsInvokeCounter < 10); }
### Question: LoggerFactory { public synchronized void useCommonsLogging() { setImplementation(JakartaCommonsLoggingImpl.class); } Logger getLog(Class<?> aClass); Logger getLog(String logger); synchronized void useCustomLogging(Class<? extends Logger> clazz); synchronized void useSlf4jLogging(); synchronized void useCommonsLogging(); synchronized void useLog4JLogging(); synchronized void useLog4J2Logging(); synchronized void useJdkLogging(); synchronized void useStdOutLogging(); synchronized void useNoLogging(); final String MARKER; }### Answer: @Test public void useCommonsLogging() { LoggerFactory.useCommonsLogging(); Logger log = LoggerFactory.getLog(Object.class); logSomething(log); assertThat(log, instanceOf(JakartaCommonsLoggingImpl.class)); }
### Question: LoggerFactory { public synchronized void useJdkLogging() { setImplementation(Jdk14LoggingImpl.class); } Logger getLog(Class<?> aClass); Logger getLog(String logger); synchronized void useCustomLogging(Class<? extends Logger> clazz); synchronized void useSlf4jLogging(); synchronized void useCommonsLogging(); synchronized void useLog4JLogging(); synchronized void useLog4J2Logging(); synchronized void useJdkLogging(); synchronized void useStdOutLogging(); synchronized void useNoLogging(); final String MARKER; }### Answer: @Test public void useJdKLogging() { LoggerFactory.useJdkLogging(); Logger log = LoggerFactory.getLog(Object.class); logSomething(log); assertThat(log, instanceOf(Jdk14LoggingImpl.class)); }
### Question: LoggerFactory { public synchronized void useNoLogging() { setImplementation(NoLoggingImpl.class); } Logger getLog(Class<?> aClass); Logger getLog(String logger); synchronized void useCustomLogging(Class<? extends Logger> clazz); synchronized void useSlf4jLogging(); synchronized void useCommonsLogging(); synchronized void useLog4JLogging(); synchronized void useLog4J2Logging(); synchronized void useJdkLogging(); synchronized void useStdOutLogging(); synchronized void useNoLogging(); final String MARKER; }### Answer: @Test public void useNoLogging() { LoggerFactory.useNoLogging(); Logger log = LoggerFactory.getLog(Object.class); logSomething(log); assertThat(log, instanceOf(NoLoggingImpl.class)); }
### Question: StringPrimitiveOperand implements PrimitiveOperand { @Override public String getValue() { return value; } StringPrimitiveOperand(@NonNull String value); @Override String getValue(); @Override String getType(); }### Answer: @Test public void operand_should_auto_unwrap_quote() { StringPrimitiveOperand operand = new StringPrimitiveOperand("\"dsdsdsdsds"); assertThat(operand.getValue(), equalTo("dsdsdsdsds")); StringPrimitiveOperand operand1 = new StringPrimitiveOperand("\"dsdsdsdsds\""); assertThat(operand1.getValue(), equalTo("dsdsdsdsds")); }
### Question: AntlrUtils { String errorLine(String errorMessage, int lineNumber) { int startIndex = 0; int endIndex = 0; for (int i = 0; i < lineNumber; i++) { int index = errorMessage.indexOf('\n', endIndex + 1); if (i > 0) { startIndex = endIndex + 1; } if (index >= 0) { endIndex = index; } else { endIndex = errorMessage.length(); } } return errorMessage.substring(startIndex, endIndex); } String underlineError(String fullText, String symbolText, int line, int charPositionInLine); }### Answer: @Test public void get_specified_line_in_multiply_line_str() throws Exception { String text = "aaa\nbbb\nccc\nddd"; assertThat(AntlrUtils.errorLine(text, 1), is("aaa")); assertThat(AntlrUtils.errorLine(text, 2), is("bbb")); assertThat(AntlrUtils.errorLine(text, 3), is("ccc")); assertThat(AntlrUtils.errorLine(text, 4), is("ddd")); }
### Question: CoffeeHouseApp implements Terminal { static void applySystemProperties(final Map<String, String> opts) { opts.forEach((key, value) -> { if (key.startsWith("-D")) System.setProperty(key.substring(2), value); }); } CoffeeHouseApp(final ActorSystem system); static void main(final String[] args); }### Answer: @Test public void applySystemPropertiesShouldConvertOptsToSystemProps() { System.setProperty("c", ""); Map<String, String> opts = new HashMap<>(); opts.put("a", "1"); opts.put("-Dc", "2"); CoffeeHouseApp.applySystemProperties(opts); assertThat(System.getProperty("c")).isEqualTo("2"); }
### Question: Barista extends AbstractLoggingActor { public static Props props(FiniteDuration prepareCoffeeDuration) { return Props.create(Barista.class, () -> new Barista(prepareCoffeeDuration)); } private Barista(FiniteDuration prepareCoffeeDuration); @Override Receive createReceive(); static Props props(FiniteDuration prepareCoffeeDuration); }### Answer: @Test public void sendingPrepareCoffeeShouldResultInCoffeePreparedResponse() { new JavaTestKit(system) {{ ActorRef barista = system.actorOf(Barista.props(duration("100 milliseconds"))); new Within(duration("50 milliseconds"), duration("1000 milliseconds")) { @Override protected void run() { barista.tell(new Barista.PrepareCoffee(new Coffee.Akkaccino(), system.deadLetters()), getRef()); expectMsgEquals(new Barista.CoffeePrepared(new Coffee.Akkaccino(), system.deadLetters())); } }; }}; }
### Question: CoffeeHouseApp implements Terminal { void createGuest(int count, Coffee coffee, int maxCoffeeCount) { for (int i = 0; i < count; i++) { coffeeHouse.tell(new CoffeeHouse.CreateGuest(coffee), ActorRef.noSender()); } } CoffeeHouseApp(final ActorSystem system); static void main(final String[] args); }### Answer: @Test public void shouldCreateNGuestsBasedOnCount() { new JavaTestKit(system) {{ new CoffeeHouseApp(system) { @Override protected ActorRef createCoffeeHouse() { return getRef(); } }.createGuest(2, new Coffee.Akkaccino(), Integer.MAX_VALUE); expectMsgAllOf(new CoffeeHouse.CreateGuest(new Coffee.Akkaccino()), new CoffeeHouse.CreateGuest(new Coffee.Akkaccino())); }}; }
### Question: CoffeeHouseApp implements Terminal { static Map<String, String> argsToOpts(final List<String> args) { final Map<String, String> opts = new HashMap<>(); for (final String arg : args) { final Matcher matcher = optPattern.matcher(arg); if (matcher.matches()) opts.put(matcher.group(1), matcher.group(2)); } return opts; } CoffeeHouseApp(final ActorSystem system); static void main(final String[] args); }### Answer: @Test public void argsToOptsShouldConvertArgsToOpts() { final Map<String, String> result = CoffeeHouseApp.argsToOpts(Arrays.asList("a=1", "b", "-Dc=2")); assertThat(result).contains(MapEntry.entry("a", "1"), MapEntry.entry("-Dc", "2")); }
### Question: Waiter extends AbstractLoggingActor { public static Props props(ActorRef barista) { return Props.create(Waiter.class, () -> new Waiter(barista)); } Waiter(ActorRef barista); @Override Receive createReceive(); static Props props(ActorRef barista); }### Answer: @Test public void sendingServeCoffeeShouldResultInPrepareCoffeeToBarista() { new JavaTestKit(system) {{ ActorRef barista = getRef(); TestProbe guest = new TestProbe(system); ActorRef waiter = system.actorOf(Waiter.props(barista)); waiter.tell(new Waiter.ServeCoffee(new Coffee.Akkaccino()), guest.ref()); expectMsgEquals(new Barista.PrepareCoffee(new Coffee.Akkaccino(), guest.ref())); }}; }
### Question: CoffeeHouse extends AbstractLoggingActor { static Props props() { return Props.create(CoffeeHouse.class, CoffeeHouse::new); } CoffeeHouse(); @Override Receive createReceive(); }### Answer: @Test public void shouldLogMessageWhenCreated() { new JavaTestKit(system) {{ interceptDebugLogMessage(this, ".*[Oo]pen.*", 1, () -> system.actorOf(CoffeeHouse.props())); }}; }
### Question: Waiter extends AbstractLoggingActor { static Props props() { return Props.create(Waiter.class, Waiter::new); } private Waiter(); @Override Receive createReceive(); }### Answer: @Test public void sendingServeCoffeeShouldResultInCoffeeServedResponse() { new JavaTestKit(system) {{ ActorRef waiter = system.actorOf(Waiter.props()); waiter.tell(new Waiter.ServeCoffee(new Coffee.Akkaccino()), getRef()); expectMsgEquals(new Waiter.CoffeeServed(new Coffee.Akkaccino())); }}; }
### Question: Guest extends AbstractLoggingActor { static Props props( final ActorRef waiter, final Coffee favoriteCoffee, FiniteDuration finishCoffeeDuration) { return Props.create(Guest.class, () -> new Guest(waiter, favoriteCoffee, finishCoffeeDuration)); } Guest(ActorRef waiter, Coffee favoriteCoffee, FiniteDuration finishCoffeeDuration); @Override Receive createReceive(); }### Answer: @Test public void sendingCoffeeServedShouldIncreaseCoffeeCount() { new JavaTestKit(system) {{ ActorRef guest = system.actorOf(Guest.props(system.deadLetters(), new Coffee.Akkaccino(), duration("100 milliseconds"))); interceptInfoLogMessage(this, ".*[Ee]njoy.*1\\.*", 1, () -> { guest.tell(new Waiter.CoffeeServed(new Coffee.Akkaccino()), ActorRef.noSender()); }); }}; }
### Question: JsonUtil { public static MessageType parseFrame(final String json) { return fromJson(json, MessageType.class); } private JsonUtil(); static T fromJson(final String json, final Class<T> type); static String toJson(final Object obj); static MessageType parseFrame(final String json); }### Answer: @Test public void parseFrame() { final String uaid = UUIDUtil.newUAID(); final String json = "{\"messageType\": \"hello\", \"uaid\": \"" + uaid + "\", \"channelIDs\": [\"123abc\", \"efg456\"]}"; final MessageType messageType = JsonUtil.parseFrame(json); assertThat(messageType.getMessageType(), is(equalTo(MessageType.Type.HELLO))); }
### Question: DefaultSimplePushServer implements SimplePushServer { @Override public HelloResponse handleHandshake(final HelloMessage handshake) { final Set<String> oldChannels = store.getChannelIds(handshake.getUAID()); for (String channelId : handshake.getChannelIds()) { if (!oldChannels.contains(channelId)) { store.saveChannel(new DefaultChannel(handshake.getUAID(), channelId, generateEndpointToken(handshake.getUAID(), channelId))); } else { oldChannels.remove(channelId); } } store.removeChannels(oldChannels); return new HelloResponseImpl(handshake.getUAID()); } DefaultSimplePushServer(final DataStore store, final SimplePushServerConfig config, final byte[] privateKey); @Override HelloResponse handleHandshake(final HelloMessage handshake); @Override RegisterResponse handleRegister(final RegisterMessage register, final String uaid); @Override Notification handleNotification(final String endpointToken, final String body); @Override UnregisterResponse handleUnregister(final UnregisterMessage unregister, final String uaid); @Override Set<Ack> handleAcknowledgement(final AckMessage ackMessage, final String uaid); @Override Set<Ack> getUnacknowledged(final String uaid); String getUAID(final String channelId); Channel getChannel(final String channelId); boolean hasChannel(final String uaid, final String channelId); boolean removeChannel(final String channnelId, final String uaid); @Override void removeAllChannels(final String uaid); @Override SimplePushServerConfig config(); static byte[] generateAndStorePrivateKey(final DataStore store, final SimplePushServerConfig config); }### Answer: @Test public void handleHandshake() { final HelloResponse response = server.handleHandshake(new HelloMessageImpl()); assertThat(response.getUAID(), is(notNullValue())); }
### Question: DefaultSimplePushServer implements SimplePushServer { @Override public RegisterResponse handleRegister(final RegisterMessage register, final String uaid) { final String channelId = register.getChannelId(); final String endpointToken = generateEndpointToken(uaid, channelId); final boolean saved = store.saveChannel(new DefaultChannel(uaid, channelId, endpointToken)); final Status status = saved ? new StatusImpl(200, "OK") : new StatusImpl(409, "Conflict: channeld [" + channelId + " is already in use"); return new RegisterResponseImpl(channelId, status, makeEndpointUrl(endpointToken)); } DefaultSimplePushServer(final DataStore store, final SimplePushServerConfig config, final byte[] privateKey); @Override HelloResponse handleHandshake(final HelloMessage handshake); @Override RegisterResponse handleRegister(final RegisterMessage register, final String uaid); @Override Notification handleNotification(final String endpointToken, final String body); @Override UnregisterResponse handleUnregister(final UnregisterMessage unregister, final String uaid); @Override Set<Ack> handleAcknowledgement(final AckMessage ackMessage, final String uaid); @Override Set<Ack> getUnacknowledged(final String uaid); String getUAID(final String channelId); Channel getChannel(final String channelId); boolean hasChannel(final String uaid, final String channelId); boolean removeChannel(final String channnelId, final String uaid); @Override void removeAllChannels(final String uaid); @Override SimplePushServerConfig config(); static byte[] generateAndStorePrivateKey(final DataStore store, final SimplePushServerConfig config); }### Answer: @Test public void handeRegister() { final RegisterResponse response = server.handleRegister(new RegisterMessageImpl("someChannelId"), UUIDUtil.newUAID()); assertThat(response.getChannelId(), equalTo("someChannelId")); assertThat(response.getMessageType(), equalTo(MessageType.Type.REGISTER)); assertThat(response.getStatus().getCode(), equalTo(200)); assertThat(response.getStatus().getMessage(), equalTo("OK")); assertThat(response.getPushEndpoint().startsWith("http: }
### Question: DefaultSimplePushServer implements SimplePushServer { public boolean removeChannel(final String channnelId, final String uaid) { try { final Channel channel = store.getChannel(channnelId); if (channel.getUAID().equals(uaid)) { store.removeChannels(new HashSet<String>(Arrays.asList(channnelId))); return true; } } catch (final ChannelNotFoundException ignored) { } return false; } DefaultSimplePushServer(final DataStore store, final SimplePushServerConfig config, final byte[] privateKey); @Override HelloResponse handleHandshake(final HelloMessage handshake); @Override RegisterResponse handleRegister(final RegisterMessage register, final String uaid); @Override Notification handleNotification(final String endpointToken, final String body); @Override UnregisterResponse handleUnregister(final UnregisterMessage unregister, final String uaid); @Override Set<Ack> handleAcknowledgement(final AckMessage ackMessage, final String uaid); @Override Set<Ack> getUnacknowledged(final String uaid); String getUAID(final String channelId); Channel getChannel(final String channelId); boolean hasChannel(final String uaid, final String channelId); boolean removeChannel(final String channnelId, final String uaid); @Override void removeAllChannels(final String uaid); @Override SimplePushServerConfig config(); static byte[] generateAndStorePrivateKey(final DataStore store, final SimplePushServerConfig config); }### Answer: @Test public void removeChannel() throws ChannelNotFoundException { final String channelId = "testChannelId"; final String uaid = UUIDUtil.newUAID(); server.handleRegister(new RegisterMessageImpl(channelId), uaid); assertThat(server.getChannel(channelId).getChannelId(), is(equalTo(channelId))); assertThat(server.removeChannel(channelId, UUIDUtil.newUAID()), is(false)); assertThat(server.removeChannel(channelId, uaid), is(true)); assertThat(server.removeChannel(channelId, uaid), is(false)); }
### Question: DefaultSimplePushServer implements SimplePushServer { public String getUAID(final String channelId) throws ChannelNotFoundException { return getChannel(channelId).getUAID(); } DefaultSimplePushServer(final DataStore store, final SimplePushServerConfig config, final byte[] privateKey); @Override HelloResponse handleHandshake(final HelloMessage handshake); @Override RegisterResponse handleRegister(final RegisterMessage register, final String uaid); @Override Notification handleNotification(final String endpointToken, final String body); @Override UnregisterResponse handleUnregister(final UnregisterMessage unregister, final String uaid); @Override Set<Ack> handleAcknowledgement(final AckMessage ackMessage, final String uaid); @Override Set<Ack> getUnacknowledged(final String uaid); String getUAID(final String channelId); Channel getChannel(final String channelId); boolean hasChannel(final String uaid, final String channelId); boolean removeChannel(final String channnelId, final String uaid); @Override void removeAllChannels(final String uaid); @Override SimplePushServerConfig config(); static byte[] generateAndStorePrivateKey(final DataStore store, final SimplePushServerConfig config); }### Answer: @Test public void getUAID() throws ChannelNotFoundException { final String channelId = UUID.randomUUID().toString(); final String uaid = UUIDUtil.newUAID(); server.handleRegister(new RegisterMessageImpl(channelId), uaid); assertThat(server.getUAID(channelId), is(equalTo(uaid))); }
### Question: WebSocketSslServerSslContext { public SSLContext sslContext() { try { final SSLContext serverContext = SSLContext.getInstance(PROTOCOL); serverContext.init(keyManagerFactory(loadKeyStore()).getKeyManagers(), null, null); return serverContext; } catch (final Exception e) { throw new RuntimeException("Failed to initialize the server-side SSLContext", e); } } WebSocketSslServerSslContext(final SockJsConfig sockJsConfig); SSLContext sslContext(); }### Answer: @Test public void createSSLEngine() { final SockJsConfig sockJsConfig = SockJsConfig.withPrefix("/echo") .tls(true) .keyStore("/simplepush-sample.keystore") .keyStorePassword("simplepush") .build(); final SSLEngine engine = new WebSocketSslServerSslContext(sockJsConfig).sslContext().createSSLEngine(); assertThat(engine, is(notNullValue())); } @Test (expected = RuntimeException.class) public void createSSLContextKeyStoreNotFound() { final SockJsConfig sockJsConfig = SockJsConfig.withPrefix("/echo") .tls(true) .keyStore("/missing.keystore") .keyStorePassword("simplepush") .build(); new WebSocketSslServerSslContext(sockJsConfig).sslContext(); }
### Question: UserAgent { public long timestamp() { return timestamp.get(); } UserAgent(final String uaid, final T transport, final long timestamp); String uaid(); T context(); long timestamp(); void timestamp(final long timestamp); @Override String toString(); }### Answer: @Test public void timestamp() { final UserAgent<ChannelHandlerContext> userAgent = new UserAgent<ChannelHandlerContext>(UUIDUtil.newUAID(), mock(ChannelHandlerContext.class), 1368781528407L); final long addedTimeout = userAgent.timestamp() + 10000; final long now = System.currentTimeMillis(); assertThat(addedTimeout < now, is(true)); }
### Question: MessageFrame extends DefaultByteBufHolder implements Frame { @Override public String toString() { return StringUtil.simpleClassName(this) + "[messages=" + messages + ']'; } MessageFrame(final String message); MessageFrame(final String... messages); MessageFrame(final List<String> messages); List<String> messages(); @Override MessageFrame copy(); @Override MessageFrame duplicate(); @Override MessageFrame retain(); @Override MessageFrame retain(int increment); @Override String toString(); }### Answer: @Test public void content() { final MessageFrame messageFrame = new MessageFrame("first", "second"); assertThat(messageFrame.content().toString(CharsetUtil.UTF_8), equalTo("a[\"first\",\"second\"]")); messageFrame.release(); }
### Question: ConfigReader { public static StandaloneConfig parse(final String fileName) throws Exception { final File configFile = new File(fileName); InputStream in = null; try { in = configFile.exists() ? new FileInputStream(configFile) : ConfigReader.class.getResourceAsStream(fileName); return parse(in); } finally { if (in != null) { in.close(); } } } private ConfigReader(); static StandaloneConfig parse(final String fileName); static StandaloneConfig parse(final InputStream in); }### Answer: @Test public void jpaDataStore() { final StandaloneConfig config = ConfigReader.parse(ConfigReaderTest.class.getResourceAsStream("/simplepush-jpa-config.json")); assertThat(config.dataStore(), is(instanceOf(JpaDataStore.class))); } @Test public void sampleConfig() { final StandaloneConfig config = ConfigReader.parse(ConfigReaderTest.class.getResourceAsStream("/simplepush-config.json")); assertThat(config.simplePushServerConfig().host(), equalTo("0.0.0.0")); assertThat(config.simplePushServerConfig().port(), is(7777)); assertThat(config.simplePushServerConfig().password(), is(notNullValue())); assertThat(config.dataStore(), is(instanceOf(InMemoryDataStore.class))); }
### Question: SimplePushSockJSService implements SockJsService { @Override public SockJsConfig config() { return sockjsConfig; } SimplePushSockJSService(final SockJsConfig sockjsConfig, final SimplePushServer simplePushServer); @Override SockJsConfig config(); @Override void onOpen(final SockJsSessionContext session); @Override @SuppressWarnings("incomplete-switch") void onMessage(final String message); @Override void onClose(); }### Answer: @Test public void rawWebSocketUpgradeRequest() throws Exception { final SimplePushServerConfig simplePushConfig = DefaultSimplePushConfig.create().password("test").build(); final SockJsConfig sockjsConf = SockJsConfig.withPrefix("/simplepush").webSocketProtocols("push-notification").build(); final byte[] privateKey = CryptoUtil.secretKey(simplePushConfig.password(), "someSaltForTesting".getBytes()); final SimplePushServer pushServer = new DefaultSimplePushServer(new InMemoryDataStore(), simplePushConfig, privateKey); final SimplePushServiceFactory factory = new SimplePushServiceFactory(sockjsConf, pushServer); final EmbeddedChannel channel = createChannel(factory); final FullHttpRequest request = websocketUpgradeRequest(factory.config().prefix() + Transports.Type.WEBSOCKET.path()); request.headers().set(Names.SEC_WEBSOCKET_PROTOCOL, "push-notification"); channel.writeInbound(request); final FullHttpResponse response = decodeFullHttpResponse(channel); assertThat(response.getStatus(), is(HttpResponseStatus.SWITCHING_PROTOCOLS)); assertThat(response.headers().get(HttpHeaders.Names.UPGRADE), equalTo("websocket")); assertThat(response.headers().get(HttpHeaders.Names.CONNECTION), equalTo("Upgrade")); assertThat(response.headers().get(Names.SEC_WEBSOCKET_PROTOCOL), equalTo("push-notification")); assertThat(response.headers().get(Names.SEC_WEBSOCKET_ACCEPT), equalTo("s3pPLMBiTxaQ9kYGzzhZRbK+xOo=")); channel.close(); }
### Question: DefaultChannel implements Channel { @Override public int hashCode() { int result = 1; result = 31 * result + ((channelId == null) ? 0 : channelId.hashCode()); result = 31 * result + ((endpointToken == null) ? 0 : endpointToken.hashCode()); result = 31 * result + (int) (version ^ (version >>> 32)); return result; } DefaultChannel(final String uaid, final String channelId, final String endpointToken); DefaultChannel(final String uaid, final String channelId, final long version, final String endpointToken); @Override String getUAID(); @Override String getChannelId(); @Override long getVersion(); @Override String getEndpointToken(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void equalsContractSymetric() { final Channel x = new DefaultChannel("test", "123abc", 1, "33ddd2elaeee"); final Channel y = new DefaultChannel("test", "123abc", 1, "33ddd2elaeee"); assertThat(x, equalTo(y)); assertThat(y, equalTo(x)); assertThat(x.hashCode(), equalTo(y.hashCode())); } @Test public void equalsContractTransitive() { final Channel x = new DefaultChannel("test", "123abc", 1, "33ddd2elaeee"); final Channel y = new DefaultChannel("test", "123abc", 1, "33ddd2elaeee"); final Channel z = new DefaultChannel("test", "123abc", 1, "33ddd2elaeee"); assertThat(x, equalTo(y)); assertThat(y, equalTo(z)); assertThat(x, equalTo(z)); assertThat(x.hashCode(), equalTo(z.hashCode())); }
### Question: DefaultChannel implements Channel { @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof Channel)) { return false; } final DefaultChannel o = (DefaultChannel) obj; return (uaid == null ? o.uaid == null : uaid.equals(o.uaid)) && (channelId == null ? o.channelId == null : channelId.equals(o.channelId)) && (endpointToken == null ? o.endpointToken == null : endpointToken.equals(o.endpointToken)) && (version == o.version); } DefaultChannel(final String uaid, final String channelId, final String endpointToken); DefaultChannel(final String uaid, final String channelId, final long version, final String endpointToken); @Override String getUAID(); @Override String getChannelId(); @Override long getVersion(); @Override String getEndpointToken(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void equalsConsistent() { final Channel x = new DefaultChannel("test", "123abc", 1, "33ddd2elaeee"); final Channel y = new DefaultChannel("test", "xyz987", 1, "33ddd2elaeee"); assertThat(x.equals(y), is(false)); } @Test public void equalsContractNull() { final Channel x = new DefaultChannel("test", "123abc", 1, "33ddd2elaeee"); assertThat(x.equals(null), is(false)); }
### Question: XhrSendTransport extends AbstractSendTransport { @Override public String toString() { return StringUtil.simpleClassName(this) + "[config=" + config + ']'; } XhrSendTransport(final SockJsConfig config); @Override void respond(final ChannelHandlerContext ctx, final FullHttpRequest request); @Override String toString(); }### Answer: @Test public void messageReceivedNoPayload() { final FullHttpResponse response = processHttpRequest(requestWithBody(null)); assertThat(response.getStatus(), equalTo(HttpResponseStatus.INTERNAL_SERVER_ERROR)); assertThat(response.getProtocolVersion(), equalTo(HttpVersion.HTTP_1_1)); assertThat(response.content().toString(UTF_8), equalTo("Payload expected.")); } @Test public void messageReceivedNoPayloadHttpVersion1_0() { final FullHttpResponse response = processHttpRequest(requestWithBody(null, HttpVersion.HTTP_1_0)); assertThat(response.getStatus(), equalTo(HttpResponseStatus.INTERNAL_SERVER_ERROR)); assertThat(response.getProtocolVersion(), equalTo(HttpVersion.HTTP_1_0)); assertThat(response.content().toString(UTF_8), equalTo("Payload expected.")); } @Test public void messageReceivedNoFormDataParameter() { final FullHttpResponse response = processHttpRequest(requestWithFormData(null)); assertThat(response.getStatus(), equalTo(HttpResponseStatus.INTERNAL_SERVER_ERROR)); assertThat(response.getProtocolVersion(), equalTo(HttpVersion.HTTP_1_1)); assertThat(response.content().toString(UTF_8), equalTo("Payload expected.")); response.release(); } @Test public void messageReceivedInvalidJson() { final String data = "[\"some message"; final FullHttpResponse response = processHttpRequest(requestWithFormData(data)); assertThat(response.getStatus(), equalTo(HttpResponseStatus.INTERNAL_SERVER_ERROR)); assertThat(response.getProtocolVersion(), equalTo(HttpVersion.HTTP_1_1)); SockJsTestUtil.verifyContentType(response, Transports.CONTENT_TYPE_PLAIN); assertThat(response.content().toString(UTF_8), equalTo("Broken JSON encoding.")); response.release(); }
### Question: AckMessageImpl implements AckMessage { @Override public Set<Ack> getAcks() { return Collections.unmodifiableSet(acks); } AckMessageImpl(final Set<Ack> acks); @Override Type getMessageType(); @Override Set<Ack> getAcks(); @Override String toString(); }### Answer: @Test public void constructWithUpdates() { final Set<Ack> acks = acks(ack("abc123", 1L), ack("efg456", 20L)); final AckMessage ack = new AckMessageImpl(acks); assertThat(ack.getAcks(), hasItems(ack("abc123", 1L), ack("efg456", 20L))); }
### Question: WebSocketHAProxyHandshaker extends WebSocketServerHandshaker00 { public static boolean isHAProxyReqeust(final FullHttpRequest request) { final String version = request.headers().get(Names.SEC_WEBSOCKET_VERSION); return version == null && request.content().readableBytes() == 0; } WebSocketHAProxyHandshaker(final String webSocketURL, final String subprotocols, final int maxFramePayloadLength); @Override ChannelFuture handshake(Channel channel, FullHttpRequest req); void addWsCodec(final ChannelFuture future); static boolean isHAProxyReqeust(final FullHttpRequest request); }### Answer: @Test public void isHAProxyRequest() { assertThat(WebSocketHAProxyHandshaker.isHAProxyReqeust(wsUpgradeRequest()), is(true)); assertThat(WebSocketHAProxyHandshaker.isHAProxyReqeust(wsUpgradeRequestWithBody()), is(false)); }
### Question: EventSourceTransport extends ChannelHandlerAdapter { @Override public void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) throws Exception { if (msg instanceof Frame) { final Frame frame = (Frame) msg; if (headerSent.compareAndSet(false, true)) { ctx.write(createResponse(CONTENT_TYPE_EVENT_STREAM), promise); ctx.writeAndFlush(new DefaultHttpContent(CRLF.duplicate())); } final ByteBuf data = ctx.alloc().buffer(); data.writeBytes(FRAME_START.duplicate()); data.writeBytes(frame.content()); data.writeBytes(FRAME_END.duplicate()); final int dataSize = data.readableBytes(); ctx.writeAndFlush(new DefaultHttpContent(data)); frame.release(); if (maxBytesLimit(dataSize)) { if (logger.isDebugEnabled()) { logger.debug("max bytesSize limit reached [{}]", config.maxStreamingBytesSize()); } ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT).addListener(ChannelFutureListener.CLOSE); } } } EventSourceTransport(final SockJsConfig config, final HttpRequest request); @Override void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise); static final String CONTENT_TYPE_EVENT_STREAM; }### Answer: @Test public void write() { final EmbeddedChannel ch = newEventSourceChannel(); ch.writeOutbound(new OpenFrame()); final HttpResponse response = ch.readOutbound(); assertThat(response.getStatus(), equalTo(HttpResponseStatus.OK)); assertThat(response.headers().get(CONTENT_TYPE), equalTo(EventSourceTransport.CONTENT_TYPE_EVENT_STREAM)); SockJsTestUtil.verifyNoCacheHeaders(response); final DefaultHttpContent newLinePrelude = ch.readOutbound(); assertThat(newLinePrelude.content().toString(UTF_8), equalTo("\r\n")); final DefaultHttpContent data = ch.readOutbound(); assertThat(data.content().toString(UTF_8), equalTo("data: o\r\n\r\n")); }
### Question: AckImpl implements Ack { @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((channelId == null) ? 0 : channelId.hashCode()); return result; } AckImpl(final String channelId, final long version); @Override String getChannelId(); @Override long getVersion(); @Override String toString(); @Override int hashCode(); @Override boolean equals(final Object obj); }### Answer: @Test public void equalsContractSymetric() { final Ack x = new AckImpl("ch1", 10L); final Ack y = new AckImpl("ch1", 10L); assertThat(x, equalTo(y)); assertThat(y, equalTo(x)); assertThat(x.hashCode(), equalTo(y.hashCode())); }
### Question: SockJsHandler extends SimpleChannelInboundHandler<FullHttpRequest> { static PathParams matches(final String path) { final Matcher matcher = SERVER_SESSION_PATTERN.matcher(path); if (matcher.find()) { final String serverId = matcher.group(1); final String sessionId = matcher.group(2); final String transport = matcher.group(3); return new MatchingSessionPath(serverId, sessionId, transport); } else { return NON_SUPPORTED_PATH; } } SockJsHandler(final SockJsServiceFactory... factories); @Override void messageReceived(final ChannelHandlerContext ctx, final FullHttpRequest request); @Override void exceptionCaught(ChannelHandlerContext ctx, Throwable cause); }### Answer: @Test public void nonMatch() { final SockJsHandler.PathParams sessionPath = SockJsHandler.matches("/xhr_send"); assertThat(sessionPath.matches(), is(false)); } @Test public void matches() { final SockJsHandler.PathParams sessionPath = SockJsHandler.matches("/000/123/xhr_send"); assertThat(sessionPath.matches(), is(true)); assertThat(sessionPath.serverId(), equalTo("000")); assertThat(sessionPath.sessionId(), equalTo("123")); assertThat(sessionPath.transport(), equalTo(Transports.Type.XHR_SEND)); }
### Question: Greeting { private Greeting() { } private Greeting(); static boolean matches(final String path); static FullHttpResponse response(final HttpRequest request); }### Answer: @Test public void greeting() throws Exception { final FullHttpResponse response = sendGreetingRequest(); assertWelcomeMessage(response); }
### Question: AckImpl implements Ack { @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof Ack)) { return false; } final AckImpl other = (AckImpl) obj; return channelId == null ? other.channelId == null : channelId.equals(other.channelId); } AckImpl(final String channelId, final long version); @Override String getChannelId(); @Override long getVersion(); @Override String toString(); @Override int hashCode(); @Override boolean equals(final Object obj); }### Answer: @Test public void equalsContractConsistent() { final Ack x = new AckImpl("ch1", 10L); final Ack y = new AckImpl("ch2", 10L); assertThat(x.equals(y), is(false)); } @Test public void equalsContractNull() { final Ack x = new AckImpl("ch1", 10L); assertThat(x.equals(null), is(false)); } @Test public void versionNotPartOfContract() { final Ack x = new AckImpl("ch1", 11L); final Ack y = new AckImpl("ch1", 12L); assertThat(x.equals(y), is(true)); }
### Question: SockJsSession { public void setState(State newState) { while (true) { final State oldState = state.get(); if (state.compareAndSet(oldState, newState)) { return; } } } SockJsSession(final String sessionId, final SockJsService service); ChannelHandlerContext connectionContext(); void setConnectionContext(final ChannelHandlerContext ctx); ChannelHandlerContext openContext(); void setOpenContext(final ChannelHandlerContext ctx); void setState(State newState); State getState(); boolean inuse(); void setInuse(final boolean use); SockJsConfig config(); String sessionId(); void onMessage(final String message); void onOpen(final SockJsSessionContext session); void onClose(); void addMessage(final String message); List<String> getAllMessages(); @SuppressWarnings("ManualArrayToCollectionCopy") void addMessages(final String[] messages); long timestamp(); @Override String toString(); }### Answer: @Test public void setState() throws Exception { final SockJsService service = mock(SockJsService.class); final SockJsSession session = new SockJsSession("123", service); session.setState(State.OPEN); assertThat(session.getState(), is(State.OPEN)); }
### Question: SockJsSession { public void onOpen(final SockJsSessionContext session) { setState(State.OPEN); service.onOpen(session); updateTimestamp(); } SockJsSession(final String sessionId, final SockJsService service); ChannelHandlerContext connectionContext(); void setConnectionContext(final ChannelHandlerContext ctx); ChannelHandlerContext openContext(); void setOpenContext(final ChannelHandlerContext ctx); void setState(State newState); State getState(); boolean inuse(); void setInuse(final boolean use); SockJsConfig config(); String sessionId(); void onMessage(final String message); void onOpen(final SockJsSessionContext session); void onClose(); void addMessage(final String message); List<String> getAllMessages(); @SuppressWarnings("ManualArrayToCollectionCopy") void addMessages(final String[] messages); long timestamp(); @Override String toString(); }### Answer: @Test public void onOpen() throws Exception { final SockJsService service = mock(SockJsService.class); final SockJsSession sockJSSession = new SockJsSession("123", service); final SockJsSessionContext session = mock(SockJsSessionContext.class); sockJSSession.onOpen(session); verify(service).onOpen(session); assertThat(sockJSSession.getState(), is(State.OPEN)); }
### Question: SockJsSession { public void onMessage(final String message) throws Exception { service.onMessage(message); updateTimestamp(); } SockJsSession(final String sessionId, final SockJsService service); ChannelHandlerContext connectionContext(); void setConnectionContext(final ChannelHandlerContext ctx); ChannelHandlerContext openContext(); void setOpenContext(final ChannelHandlerContext ctx); void setState(State newState); State getState(); boolean inuse(); void setInuse(final boolean use); SockJsConfig config(); String sessionId(); void onMessage(final String message); void onOpen(final SockJsSessionContext session); void onClose(); void addMessage(final String message); List<String> getAllMessages(); @SuppressWarnings("ManualArrayToCollectionCopy") void addMessages(final String[] messages); long timestamp(); @Override String toString(); }### Answer: @Test public void onMessage() throws Exception { final SockJsService service = mock(SockJsService.class); final SockJsSession sockJSSession = new SockJsSession("123", service); sockJSSession.onMessage("testing"); verify(service).onMessage("testing"); }
### Question: SockJsSession { public void onClose() { setState(State.CLOSED); service.onClose(); } SockJsSession(final String sessionId, final SockJsService service); ChannelHandlerContext connectionContext(); void setConnectionContext(final ChannelHandlerContext ctx); ChannelHandlerContext openContext(); void setOpenContext(final ChannelHandlerContext ctx); void setState(State newState); State getState(); boolean inuse(); void setInuse(final boolean use); SockJsConfig config(); String sessionId(); void onMessage(final String message); void onOpen(final SockJsSessionContext session); void onClose(); void addMessage(final String message); List<String> getAllMessages(); @SuppressWarnings("ManualArrayToCollectionCopy") void addMessages(final String[] messages); long timestamp(); @Override String toString(); }### Answer: @Test public void onClose() throws Exception { final SockJsService service = mock(SockJsService.class); final SockJsSession sockJSSession = new SockJsSession("123", service); sockJSSession.onClose(); verify(service).onClose(); }
### Question: SockJsSession { public void addMessage(final String message) { messageQueue.add(message); updateTimestamp(); } SockJsSession(final String sessionId, final SockJsService service); ChannelHandlerContext connectionContext(); void setConnectionContext(final ChannelHandlerContext ctx); ChannelHandlerContext openContext(); void setOpenContext(final ChannelHandlerContext ctx); void setState(State newState); State getState(); boolean inuse(); void setInuse(final boolean use); SockJsConfig config(); String sessionId(); void onMessage(final String message); void onOpen(final SockJsSessionContext session); void onClose(); void addMessage(final String message); List<String> getAllMessages(); @SuppressWarnings("ManualArrayToCollectionCopy") void addMessages(final String[] messages); long timestamp(); @Override String toString(); }### Answer: @Test public void addMessage() throws Exception { final SockJsService service = mock(SockJsService.class); final SockJsSession sockJSSession = new SockJsSession("123", service); sockJSSession.addMessage("hello"); assertThat(sockJSSession.getAllMessages().size(), is(1)); }
### Question: SockJsSession { @SuppressWarnings("ManualArrayToCollectionCopy") public void addMessages(final String[] messages) { for (String msg: messages) { messageQueue.add(msg); } } SockJsSession(final String sessionId, final SockJsService service); ChannelHandlerContext connectionContext(); void setConnectionContext(final ChannelHandlerContext ctx); ChannelHandlerContext openContext(); void setOpenContext(final ChannelHandlerContext ctx); void setState(State newState); State getState(); boolean inuse(); void setInuse(final boolean use); SockJsConfig config(); String sessionId(); void onMessage(final String message); void onOpen(final SockJsSessionContext session); void onClose(); void addMessage(final String message); List<String> getAllMessages(); @SuppressWarnings("ManualArrayToCollectionCopy") void addMessages(final String[] messages); long timestamp(); @Override String toString(); }### Answer: @Test public void addMessages() throws Exception { final SockJsService service = mock(SockJsService.class); final SockJsSession sockJSSession = new SockJsSession("123", service); sockJSSession.addMessages(new String[]{"hello", "world"}); final List<String> messages = sockJSSession.getAllMessages(); assertThat(messages.size(), is(2)); assertThat(messages.get(0), equalTo("hello")); assertThat(messages.get(1), equalTo("world")); assertThat(sockJSSession.getAllMessages().size(), is(0)); }
### Question: VersionExtractor { public static String extractVersion(final String payload) { if (payload == null || "".equals(payload)) { return String.valueOf(System.currentTimeMillis()); } final Matcher matcher = VERSION_PATTERN.matcher(payload); if (matcher.find()) { return matcher.group(1); } throw new RuntimeException("Could not find a version in payload [" + payload + "]"); } private VersionExtractor(); static String extractVersion(final String payload); }### Answer: @Test public void extractVersion() { assertThat(VersionExtractor.extractVersion("version=1"), equalTo("1")); assertThat(VersionExtractor.extractVersion("version= 2"), equalTo("2")); assertThat(VersionExtractor.extractVersion("version =3"), equalTo("3")); assertThat(VersionExtractor.extractVersion(" version=10"), equalTo("10")); assertThat(VersionExtractor.extractVersion(" version= 11"), equalTo("11")); assertThat(VersionExtractor.extractVersion(" version = 12 "), equalTo("12")); } @Test public void noVersion() { assertThat(VersionExtractor.extractVersion(""), is(notNullValue())); assertThat(VersionExtractor.extractVersion(null), is(notNullValue())); } @Test (expected = RuntimeException.class) public void invalidVersionPropertyName() { VersionExtractor.extractVersion("vorsion=12"); } @Test (expected = RuntimeException.class) public void invalidVersion() { VersionExtractor.extractVersion("version="); }
### Question: CryptoUtil { public static String encrypt(final byte[] key, final String content) throws Exception { final byte[] iv = BlockCipher.getIV(); final byte[] encrypted = new CryptoBox(key).encrypt(iv, content.getBytes(ASCII)); final String base64 = new UrlBase64().encode(prependIV(encrypted, iv)); return URLEncoder.encode(base64, ASCII.displayName()); } private CryptoUtil(); static String encrypt(final byte[] key, final String content); static String decrypt(final byte[] key, final String content); static byte[] secretKey(final String password, final byte[] salt); static String endpointToken(final String uaid, final String channelId, final byte[] key); }### Answer: @Test public void encrypt() throws Exception { final byte[] salt = "some salt for the server private".getBytes(); final byte[] key = CryptoUtil.secretKey("key", salt); final String encrypted = CryptoUtil.encrypt(key, "some string to encrypt"); assertThat(encrypted, is(notNullValue())); }
### Question: CryptoUtil { public static String decrypt(final byte[] key, final String content) throws Exception { final byte[] decodedContent = new UrlBase64().decode(URLDecoder.decode(content, ASCII.displayName())); final byte[] iv = extractIV(decodedContent); final byte[] decrypted = new CryptoBox(key).decrypt(iv, extractContent(decodedContent)); return new String(decrypted, ASCII); } private CryptoUtil(); static String encrypt(final byte[] key, final String content); static String decrypt(final byte[] key, final String content); static byte[] secretKey(final String password, final byte[] salt); static String endpointToken(final String uaid, final String channelId, final byte[] key); }### Answer: @Test public void decrypt() throws Exception { final byte[] salt = "some salt for the server private".getBytes(); final byte[] encryptKey = CryptoUtil.secretKey("key", salt); final String expected = UUID.randomUUID().toString() + "." + UUID.randomUUID().toString(); final String encrypted = CryptoUtil.encrypt(encryptKey, expected); final byte[] decryptKey = CryptoUtil.secretKey("key", salt); assertThat(CryptoUtil.decrypt(decryptKey, encrypted), is(equalTo(expected))); }
### Question: RedisDataStore implements DataStore { @Override public boolean saveChannel(final Channel channel) { final Jedis jedis = jedisPool.getResource(); try { final String uaid = channel.getUAID(); final String chid = channel.getChannelId(); if (jedis.sismember(uaidLookupKey(uaid), chid)) { return false; } final String endpointToken = channel.getEndpointToken(); final Transaction tx = jedis.multi(); tx.set(endpointToken, Long.toString(channel.getVersion())); tx.set(tokenLookupKey(endpointToken), chid); tx.hmset(chidLookupKey(chid), mapOf(endpointToken, uaid)); tx.sadd(uaidLookupKey(uaid), chid); tx.exec(); return true; } finally { jedisPool.returnResource(jedis); } } RedisDataStore(final String host, final int port); @Override void savePrivateKeySalt(final byte[] salt); @Override byte[] getPrivateKeySalt(); @Override boolean saveChannel(final Channel channel); @Override void removeChannels(final Set<String> channelIds); @Override Channel getChannel(final String channelId); @Override Set<String> getChannelIds(final String uaid); @Override void removeChannels(final String uaid); @Override String updateVersion(final String endpointToken, final long newVersion); @Override String saveUnacknowledged(final String channelId, final long version); @Override Set<Ack> getUnacknowledged(final String uaid); @Override Set<Ack> removeAcknowledged(final String uaid, final Set<Ack> acks); }### Answer: @Test public void saveChannel() { final Channel channel = newChannel2(); assertThat(newRedisDataStore().saveChannel(channel), is(true)); } @Test public void saveChannelDuplicate() { final Channel channel = newChannel2(); assertThat(newRedisDataStore().saveChannel(channel), is(true)); assertThat(newRedisDataStore().saveChannel(channel), is(false)); }
### Question: RedisDataStore implements DataStore { @Override public Set<String> getChannelIds(final String uaid) { final Jedis jedis = jedisPool.getResource(); try { return jedis.smembers(uaidLookupKey(uaid)); } finally { jedisPool.returnResource(jedis); } } RedisDataStore(final String host, final int port); @Override void savePrivateKeySalt(final byte[] salt); @Override byte[] getPrivateKeySalt(); @Override boolean saveChannel(final Channel channel); @Override void removeChannels(final Set<String> channelIds); @Override Channel getChannel(final String channelId); @Override Set<String> getChannelIds(final String uaid); @Override void removeChannels(final String uaid); @Override String updateVersion(final String endpointToken, final long newVersion); @Override String saveUnacknowledged(final String channelId, final long version); @Override Set<Ack> getUnacknowledged(final String uaid); @Override Set<Ack> removeAcknowledged(final String uaid, final Set<Ack> acks); }### Answer: @Test public void getChannelIds() throws ChannelNotFoundException { final RedisDataStore store = newRedisDataStore(); final String uaid = UUIDUtil.newUAID(); store.saveChannel(newChannel2(uaid)); store.saveChannel(newChannel2(uaid)); final Set<String> channelIds = store.getChannelIds(uaid); assertThat(channelIds.size(), is(2)); }
### Question: RedisDataStore implements DataStore { @Override public void removeChannels(final Set<String> channelIds) { for (String channelId : channelIds) { removeChannel(channelId); } } RedisDataStore(final String host, final int port); @Override void savePrivateKeySalt(final byte[] salt); @Override byte[] getPrivateKeySalt(); @Override boolean saveChannel(final Channel channel); @Override void removeChannels(final Set<String> channelIds); @Override Channel getChannel(final String channelId); @Override Set<String> getChannelIds(final String uaid); @Override void removeChannels(final String uaid); @Override String updateVersion(final String endpointToken, final long newVersion); @Override String saveUnacknowledged(final String channelId, final long version); @Override Set<Ack> getUnacknowledged(final String uaid); @Override Set<Ack> removeAcknowledged(final String uaid, final Set<Ack> acks); }### Answer: @Test public void removeChannels() throws ChannelNotFoundException { final RedisDataStore store = newRedisDataStore(); final String uaid = UUIDUtil.newUAID(); final Channel ch1 = newChannel2(uaid); final Channel ch2 = newChannel2(uaid); store.saveChannel(ch1); store.saveChannel(ch2); store.removeChannels(new HashSet<String>(Arrays.asList(ch1.getChannelId(), ch2.getChannelId()))); assertThat(store.getChannelIds(uaid).size(), is(0)); }
### Question: RedisDataStore implements DataStore { @Override public String updateVersion(final String endpointToken, final long newVersion) throws VersionException, ChannelNotFoundException { final Jedis jedis = jedisPool.getResource(); try { jedis.watch(endpointToken); final String versionString = jedis.get(endpointToken); if (versionString == null) { throw channelNotFoundException(endpointToken); } final long currentVersion = Long.valueOf(versionString); if (newVersion <= currentVersion) { throw new VersionException("version [" + newVersion + "] must be greater than the current version [" + currentVersion + "]"); } final Transaction tx = jedis.multi(); tx.set(endpointToken, String.valueOf(newVersion)); tx.exec(); logger.debug(tokenLookupKey(endpointToken)); return jedis.get(tokenLookupKey(endpointToken)); } finally { jedisPool.returnResource(jedis); } } RedisDataStore(final String host, final int port); @Override void savePrivateKeySalt(final byte[] salt); @Override byte[] getPrivateKeySalt(); @Override boolean saveChannel(final Channel channel); @Override void removeChannels(final Set<String> channelIds); @Override Channel getChannel(final String channelId); @Override Set<String> getChannelIds(final String uaid); @Override void removeChannels(final String uaid); @Override String updateVersion(final String endpointToken, final long newVersion); @Override String saveUnacknowledged(final String channelId, final long version); @Override Set<Ack> getUnacknowledged(final String uaid); @Override Set<Ack> removeAcknowledged(final String uaid, final Set<Ack> acks); }### Answer: @Test public void updateVersion() throws VersionException, ChannelNotFoundException { final RedisDataStore store = newRedisDataStore(); final Channel channel = newChannel2(); store.saveChannel(channel); final String channelId = store.updateVersion(channel.getEndpointToken(), 2L); assertThat(channelId, equalTo(channel.getChannelId())); }
### Question: RedisDataStore implements DataStore { @Override public String saveUnacknowledged(final String channelId, final long version) { final Jedis jedis = jedisPool.getResource(); try { jedis.set(ackLookupKey(channelId), Long.toString(version)); final List<String> hashValues = jedis.hmget(chidLookupKey(channelId), UAID_KEY); final String uaid = hashValues.get(0); jedis.sadd(acksLookupKey(uaid), channelId); return uaid; } finally { jedisPool.returnResource(jedis); } } RedisDataStore(final String host, final int port); @Override void savePrivateKeySalt(final byte[] salt); @Override byte[] getPrivateKeySalt(); @Override boolean saveChannel(final Channel channel); @Override void removeChannels(final Set<String> channelIds); @Override Channel getChannel(final String channelId); @Override Set<String> getChannelIds(final String uaid); @Override void removeChannels(final String uaid); @Override String updateVersion(final String endpointToken, final long newVersion); @Override String saveUnacknowledged(final String channelId, final long version); @Override Set<Ack> getUnacknowledged(final String uaid); @Override Set<Ack> removeAcknowledged(final String uaid, final Set<Ack> acks); }### Answer: @Test public void saveUnacknowledged() { final RedisDataStore store = newRedisDataStore(); final Channel channel = newChannel2(); store.saveChannel(channel); store.saveUnacknowledged(channel.getChannelId(), channel.getVersion()); final Set<Ack> unacknowledged = store.getUnacknowledged(channel.getUAID()); assertThat(unacknowledged.size(), is(1)); }
### Question: InMemoryDataStore implements DataStore { @Override public boolean saveChannel(final Channel ch) { checkNotNull(ch, "ch"); final MutableChannel mutableChannel = new MutableChannel(ch); final Channel previous = channels.putIfAbsent(ch.getChannelId(), mutableChannel); endpoints.put(ch.getEndpointToken(), mutableChannel); return previous == null; } @Override void savePrivateKeySalt(final byte[] salt); @Override byte[] getPrivateKeySalt(); @Override boolean saveChannel(final Channel ch); @Override Channel getChannel(final String channelId); @Override void removeChannels(final String uaid); @Override void removeChannels(final Set<String> channelIds); @Override Set<String> getChannelIds(final String uaid); @Override String updateVersion(final String endpointToken, final long version); @Override String saveUnacknowledged(final String channelId, final long version); @Override Set<Ack> getUnacknowledged(final String uaid); @Override Set<Ack> removeAcknowledged(final String uaid, final Set<Ack> acked); }### Answer: @Test public void saveChannel() { final InMemoryDataStore store = new InMemoryDataStore(); final Channel channel = mockChannel(UUIDUtil.newUAID(), "channel-1", 1, "endpointToken"); final boolean saved = store.saveChannel(channel); assertThat(saved, is(true)); }
### Question: HelloMessageImpl implements HelloMessage { @Override public Set<String> getChannelIds() { return Collections.unmodifiableSet(channelIds); } HelloMessageImpl(); HelloMessageImpl(final String uaid); HelloMessageImpl(final String uaid, final Set<String> channelIds); @Override String getUAID(); @Override Set<String> getChannelIds(); @Override Type getMessageType(); @Override String toString(); }### Answer: @Test(expected = UnsupportedOperationException.class) public void channelIdsUnmodifiable() { final HelloMessageImpl handshake = new HelloMessageImpl(newUAID(), channelIds("123abc", "efg456")); handshake.getChannelIds().remove("123abc"); }
### Question: InMemoryDataStore implements DataStore { @Override public Channel getChannel(final String channelId) throws ChannelNotFoundException { checkNotNull(channelId, "channelId"); final Channel channel = channels.get(channelId); if (channel == null) { throw new ChannelNotFoundException("No Channel for [" + channelId + "] was found", channelId); } return channel; } @Override void savePrivateKeySalt(final byte[] salt); @Override byte[] getPrivateKeySalt(); @Override boolean saveChannel(final Channel ch); @Override Channel getChannel(final String channelId); @Override void removeChannels(final String uaid); @Override void removeChannels(final Set<String> channelIds); @Override Set<String> getChannelIds(final String uaid); @Override String updateVersion(final String endpointToken, final long version); @Override String saveUnacknowledged(final String channelId, final long version); @Override Set<Ack> getUnacknowledged(final String uaid); @Override Set<Ack> removeAcknowledged(final String uaid, final Set<Ack> acked); }### Answer: @Test public void getChannel() throws ChannelNotFoundException { final InMemoryDataStore store = new InMemoryDataStore(); store.saveChannel(mockChannel(UUIDUtil.newUAID(), "channel-1", 1, "endpointToken")); final Channel channel = store.getChannel("channel-1"); assertThat(channel, is(notNullValue())); assertThat(channel.getChannelId(), equalTo("channel-1")); assertThat(channel.getEndpointToken(), equalTo("endpointToken")); }
### Question: InMemoryDataStore implements DataStore { private boolean removeChannel(final String channelId) { checkNotNull(channelId, "channelId"); final Channel channel = channels.remove(channelId); if (channel != null) { endpoints.remove(endpoints.get(channel.getEndpointToken())); } return channel != null; } @Override void savePrivateKeySalt(final byte[] salt); @Override byte[] getPrivateKeySalt(); @Override boolean saveChannel(final Channel ch); @Override Channel getChannel(final String channelId); @Override void removeChannels(final String uaid); @Override void removeChannels(final Set<String> channelIds); @Override Set<String> getChannelIds(final String uaid); @Override String updateVersion(final String endpointToken, final long version); @Override String saveUnacknowledged(final String channelId, final long version); @Override Set<Ack> getUnacknowledged(final String uaid); @Override Set<Ack> removeAcknowledged(final String uaid, final Set<Ack> acked); }### Answer: @Test public void removeChannel() { final InMemoryDataStore store = new InMemoryDataStore(); store.saveChannel(mockChannel(UUIDUtil.newUAID(), "channel-1", 1, "endpointToken")); store.removeChannels(new HashSet<String>(Arrays.asList("channel-1"))); assertThat(hasChannel("channel-1", store), is(false)); }
### Question: InMemoryDataStore implements DataStore { @Override public void removeChannels(final String uaid) { checkNotNull(uaid, "uaid"); for (Channel channel : channels.values()) { if (channel.getUAID().equals(uaid)) { removeChannel(channel.getChannelId()); logger.info("Removing [" + channel.getChannelId() + "] for UserAgent [" + uaid + "]"); } } unacked.remove(uaid); } @Override void savePrivateKeySalt(final byte[] salt); @Override byte[] getPrivateKeySalt(); @Override boolean saveChannel(final Channel ch); @Override Channel getChannel(final String channelId); @Override void removeChannels(final String uaid); @Override void removeChannels(final Set<String> channelIds); @Override Set<String> getChannelIds(final String uaid); @Override String updateVersion(final String endpointToken, final long version); @Override String saveUnacknowledged(final String channelId, final long version); @Override Set<Ack> getUnacknowledged(final String uaid); @Override Set<Ack> removeAcknowledged(final String uaid, final Set<Ack> acked); }### Answer: @Test public void removeChannels() throws ChannelNotFoundException { final InMemoryDataStore store = new InMemoryDataStore(); final String uaid1 = UUIDUtil.newUAID(); final String uaid2 = UUIDUtil.newUAID(); store.saveChannel(mockChannel(uaid1, "channel-1", 1, "endpointToken1")); store.saveChannel(mockChannel(uaid2, "channel-2", 1, "endpointToken2")); store.saveChannel(mockChannel(uaid1, "channel-3", 1, "endpointToken3")); store.saveChannel(mockChannel(uaid2, "channel-4", 1, "endpointToken4")); store.removeChannels(uaid2); assertThat(hasChannel("channel-1", store), is(true)); assertThat(hasChannel("channel-2", store), is(false)); assertThat(hasChannel("channel-3", store), is(true)); assertThat(hasChannel("channel-4", store), is(false)); }
### Question: CouchDBDataStore implements DataStore { @Override public void savePrivateKeySalt(final byte[] salt) { final byte[] privateKeySalt = getPrivateKeySalt(); if (privateKeySalt.length == 0) { final Map<String, String> map = new HashMap<String, String>(2); map.put(TYPE_FIELD, Views.SERVER.viewName()); map.put("salt", new String(salt, UTF_8)); db.create(map); } } CouchDBDataStore(final String url, final String dbName); @Override void savePrivateKeySalt(final byte[] salt); @Override byte[] getPrivateKeySalt(); @Override boolean saveChannel(final Channel channel); @Override Channel getChannel(final String channelId); @Override void removeChannels(final String uaid); @Override void removeChannels(final Set<String> channelIds); @Override Set<String> getChannelIds(final String uaid); @Override String updateVersion(final String endpointToken, final long version); @Override String saveUnacknowledged(final String channelId, final long version); @Override Set<Ack> getUnacknowledged(final String uaid); @Override Set<Ack> removeAcknowledged(final String uaid, final Set<Ack> acked); }### Answer: @Test public void savePrivateKeySalt() { final byte[] salt = "some private salt".getBytes(); datastore.savePrivateKeySalt(salt); assertThat(datastore.getPrivateKeySalt(), equalTo(salt)); }
### Question: CouchDBDataStore implements DataStore { @Override public boolean saveChannel(final Channel channel) { db.create(channelAsMap(channel)); return true; } CouchDBDataStore(final String url, final String dbName); @Override void savePrivateKeySalt(final byte[] salt); @Override byte[] getPrivateKeySalt(); @Override boolean saveChannel(final Channel channel); @Override Channel getChannel(final String channelId); @Override void removeChannels(final String uaid); @Override void removeChannels(final Set<String> channelIds); @Override Set<String> getChannelIds(final String uaid); @Override String updateVersion(final String endpointToken, final long version); @Override String saveUnacknowledged(final String channelId, final long version); @Override Set<Ack> getUnacknowledged(final String uaid); @Override Set<Ack> removeAcknowledged(final String uaid, final Set<Ack> acked); }### Answer: @Test public void saveChannel() { final Channel channel = newChannel(UUIDUtil.newUAID(), UUID.randomUUID().toString()); final boolean saved = datastore.saveChannel(channel); assertThat(saved, is(true)); } @Test public void saveChannelWithIdContainingUnderscore() { final String uaid = UUIDUtil.newUAID(); final String channelId = UUID.randomUUID().toString(); final byte[] keySalt = "some string as a salt".getBytes(); final String endpointToken = CryptoUtil.endpointToken(uaid, channelId, CryptoUtil.secretKey("testKey", keySalt)); final Channel channel = new DefaultChannel(uaid, channelId, "_" + endpointToken); final boolean saved = datastore.saveChannel(channel); assertThat(saved, is(true)); }
### Question: CouchDBDataStore implements DataStore { @Override public Channel getChannel(final String channelId) throws ChannelNotFoundException { return channelFromJson(getChannelJson(channelId)); } CouchDBDataStore(final String url, final String dbName); @Override void savePrivateKeySalt(final byte[] salt); @Override byte[] getPrivateKeySalt(); @Override boolean saveChannel(final Channel channel); @Override Channel getChannel(final String channelId); @Override void removeChannels(final String uaid); @Override void removeChannels(final Set<String> channelIds); @Override Set<String> getChannelIds(final String uaid); @Override String updateVersion(final String endpointToken, final long version); @Override String saveUnacknowledged(final String channelId, final long version); @Override Set<Ack> getUnacknowledged(final String uaid); @Override Set<Ack> removeAcknowledged(final String uaid, final Set<Ack> acked); }### Answer: @Test (expected = ChannelNotFoundException.class) public void getChannelNonExisting() throws ChannelNotFoundException { datastore.getChannel(UUID.randomUUID().toString()); } @Test public void getChannel() throws ChannelNotFoundException { final String uaid = UUIDUtil.newUAID(); final String channelId = UUID.randomUUID().toString(); final Channel channel = newChannel(uaid, channelId); datastore.saveChannel(channel); final Channel retreived = datastore.getChannel(channelId); assertThat(retreived.getUAID(), is(equalTo(channel.getUAID()))); assertThat(retreived.getChannelId(), is(equalTo(channel.getChannelId()))); assertThat(retreived.getEndpointToken(), is(equalTo(channel.getEndpointToken()))); assertThat(retreived.getVersion(), is(channel.getVersion())); }
### Question: CouchDBDataStore implements DataStore { @Override public void removeChannels(final String uaid) { final ViewResult viewResult = db.queryView(query(Views.UAID.viewName(), uaid)); final List<Row> rows = viewResult.getRows(); final Set<String> channelIds = new HashSet<String>(rows.size()); for (Row row : rows) { final JsonNode json = row.getValueAsNode().get(DOC_FIELD); channelIds.add(json.get(CHID_FIELD).asText()); } removeChannels(channelIds); } CouchDBDataStore(final String url, final String dbName); @Override void savePrivateKeySalt(final byte[] salt); @Override byte[] getPrivateKeySalt(); @Override boolean saveChannel(final Channel channel); @Override Channel getChannel(final String channelId); @Override void removeChannels(final String uaid); @Override void removeChannels(final Set<String> channelIds); @Override Set<String> getChannelIds(final String uaid); @Override String updateVersion(final String endpointToken, final long version); @Override String saveUnacknowledged(final String channelId, final long version); @Override Set<Ack> getUnacknowledged(final String uaid); @Override Set<Ack> removeAcknowledged(final String uaid, final Set<Ack> acked); }### Answer: @Test (expected = ChannelNotFoundException.class) public void removeChannels() throws ChannelNotFoundException { final String uaid = UUIDUtil.newUAID(); final String channelId = UUID.randomUUID().toString(); datastore.saveChannel(newChannel(uaid, channelId)); datastore.saveChannel(newChannel(uaid, UUID.randomUUID().toString())); datastore.removeChannels(uaid); datastore.getChannel(channelId); }
### Question: OpenFrame extends DefaultByteBufHolder implements Frame { @Override public String toString() { return StringUtil.simpleClassName(this) + "[o]"; } OpenFrame(); @Override String toString(); @Override OpenFrame copy(); @Override OpenFrame duplicate(); @Override OpenFrame retain(); @Override OpenFrame retain(int increment); }### Answer: @Test public void content() { assertThat(new OpenFrame().content().toString(CharsetUtil.UTF_8), equalTo("o")); }
### Question: CouchDBDataStore implements DataStore { @Override public Set<String> getChannelIds(final String uaid) { final ViewResult viewResult = db.queryView(query(Views.UAID.viewName(), uaid)); final List<Row> rows = viewResult.getRows(); if (rows.isEmpty()) { return Collections.emptySet(); } final Set<String> channelIds = new HashSet<String> (rows.size()); for (Row row : rows) { channelIds.add(row.getValueAsNode().get(DOC_FIELD).get(CHID_FIELD).asText()); } return channelIds; } CouchDBDataStore(final String url, final String dbName); @Override void savePrivateKeySalt(final byte[] salt); @Override byte[] getPrivateKeySalt(); @Override boolean saveChannel(final Channel channel); @Override Channel getChannel(final String channelId); @Override void removeChannels(final String uaid); @Override void removeChannels(final Set<String> channelIds); @Override Set<String> getChannelIds(final String uaid); @Override String updateVersion(final String endpointToken, final long version); @Override String saveUnacknowledged(final String channelId, final long version); @Override Set<Ack> getUnacknowledged(final String uaid); @Override Set<Ack> removeAcknowledged(final String uaid, final Set<Ack> acked); }### Answer: @Test public void removeChannelIdsEmpty() throws ChannelNotFoundException { final Set<String> channelIds = datastore.getChannelIds(UUIDUtil.newUAID()); assertThat(channelIds.isEmpty(), is(true)); }
### Question: CouchDBDataStore implements DataStore { @Override public String saveUnacknowledged(final String channelId, final long version) throws ChannelNotFoundException { final JsonNode json = getChannelJson(channelId); final Map<String, String> unack = docToAckMap((ObjectNode) json.get(DOC_FIELD), version); db.create(unack); return unack.get(UAID_FIELD); } CouchDBDataStore(final String url, final String dbName); @Override void savePrivateKeySalt(final byte[] salt); @Override byte[] getPrivateKeySalt(); @Override boolean saveChannel(final Channel channel); @Override Channel getChannel(final String channelId); @Override void removeChannels(final String uaid); @Override void removeChannels(final Set<String> channelIds); @Override Set<String> getChannelIds(final String uaid); @Override String updateVersion(final String endpointToken, final long version); @Override String saveUnacknowledged(final String channelId, final long version); @Override Set<Ack> getUnacknowledged(final String uaid); @Override Set<Ack> removeAcknowledged(final String uaid, final Set<Ack> acked); }### Answer: @Test public void saveUnacknowledged() throws ChannelNotFoundException { final String uaid = UUIDUtil.newUAID(); final Channel channel = newChannel(uaid, UUID.randomUUID().toString(), 10); datastore.saveChannel(channel); final String savedUaid = datastore.saveUnacknowledged(channel.getChannelId(), channel.getVersion()); assertThat(savedUaid, is(equalTo(uaid))); }
### Question: CouchDBDataStore implements DataStore { @Override public Set<Ack> getUnacknowledged(final String uaid) { final ViewResult viewResult = db.queryView(query(Views.UNACKS.viewName(), uaid)); return rowsToAcks(viewResult.getRows()); } CouchDBDataStore(final String url, final String dbName); @Override void savePrivateKeySalt(final byte[] salt); @Override byte[] getPrivateKeySalt(); @Override boolean saveChannel(final Channel channel); @Override Channel getChannel(final String channelId); @Override void removeChannels(final String uaid); @Override void removeChannels(final Set<String> channelIds); @Override Set<String> getChannelIds(final String uaid); @Override String updateVersion(final String endpointToken, final long version); @Override String saveUnacknowledged(final String channelId, final long version); @Override Set<Ack> getUnacknowledged(final String uaid); @Override Set<Ack> removeAcknowledged(final String uaid, final Set<Ack> acked); }### Answer: @Test public void getUnacknowledged() throws ChannelNotFoundException { final String uaid = UUIDUtil.newUAID(); final Channel channel = newChannel(uaid, UUID.randomUUID().toString(), 10); datastore.saveChannel(channel); datastore.saveUnacknowledged(channel.getChannelId(), channel.getVersion()); final Set<Ack> unacks = datastore.getUnacknowledged(uaid); assertThat(unacks, hasItems(ack(channel))); }
### Question: ChannelDTO implements Serializable { @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final ChannelDTO other = (ChannelDTO) obj; return channelId == null ? other.channelId == null : channelId.equals(other.channelId) && endpointToken == null ? other.endpointToken == null : endpointToken.equals(other.endpointToken); } protected ChannelDTO(); ChannelDTO(final UserAgentDTO userAgent, final String channelId, final long version, final String endpointToken); String getChannelId(); long getVersion(); void setVersion(final long version); String getEndpointToken(); UserAgentDTO getUserAgent(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void equalsContractReflexive() { final ChannelDTO x = new ChannelDTO(new UserAgentDTO(uaid), channelId, version, endpointUrl); assertThat(x.equals(x), is(true)); } @Test public void equalsContractSymmetric() { final ChannelDTO x = new ChannelDTO(new UserAgentDTO(uaid), channelId, version, endpointUrl); final ChannelDTO y = new ChannelDTO(new UserAgentDTO(uaid), channelId, version, endpointUrl); assertThat(x.equals(y), is(true)); assertThat(y.equals(x), is(true)); } @Test public void equalsContractTransative() { final ChannelDTO x = new ChannelDTO(new UserAgentDTO(uaid), channelId, version, endpointUrl); final ChannelDTO y = new ChannelDTO(new UserAgentDTO(uaid), channelId, version, endpointUrl); final ChannelDTO z = new ChannelDTO(new UserAgentDTO(uaid), channelId, version, endpointUrl); assertThat(x.equals(y), is(true)); assertThat(y.equals(z), is(true)); assertThat(x.equals(z), is(true)); } @Test public void equalsContractNull() { final ChannelDTO x = new ChannelDTO(new UserAgentDTO(uaid), channelId, version, endpointUrl); assertThat(x.equals(null), is(false)); }
### Question: CloseFrame extends DefaultByteBufHolder implements Frame { @Override public String toString() { return StringUtil.simpleClassName(this) + "[statusCode=" + statusCode + ", statusMsg='" + statusMsg + "']"; } CloseFrame(final int statusCode, final String statusMsg); int statusCode(); String statusMsg(); @Override String toString(); @Override CloseFrame copy(); @Override CloseFrame duplicate(); @Override CloseFrame retain(); @Override CloseFrame retain(int increment); }### Answer: @Test public void content() { final CloseFrame closeFrame = new CloseFrame(3000, "Go away!"); assertThat(closeFrame.content().toString(CharsetUtil.UTF_8), equalTo("c[3000,\"Go away!\"]")); closeFrame.release(); }
### Question: JpaDataStore implements DataStore { @Override public void savePrivateKeySalt(final byte[] salt) { final byte[] privateKeySalt = getPrivateKeySalt(); if (privateKeySalt.length != 0) { return; } final JpaOperation<Void> saveSalt = new JpaOperation<Void>() { @Override public Void perform(final EntityManager em) { em.persist(new Server(new String(salt, UTF_8))); return null; } }; jpaExecutor.execute(saveSalt); } JpaDataStore(final String persistenceUnit); @Override void savePrivateKeySalt(final byte[] salt); @Override byte[] getPrivateKeySalt(); @Override boolean saveChannel(final Channel channel); @Override Channel getChannel(final String channelId); @Override void removeChannels(final Set<String> channelIds); @Override Set<String> getChannelIds(final String uaid); @Override void removeChannels(final String uaid); @Override String updateVersion(final String endpointToken, final long version); @Override String saveUnacknowledged(final String channelId, final long version); @Override Set<Ack> getUnacknowledged(final String uaid); @Override Set<Ack> removeAcknowledged(final String uaid, final Set<Ack> acked); }### Answer: @Test public void savePrivateKeySalt() { final byte[] salt = "some private salt".getBytes(); jpaDataStore.savePrivateKeySalt(salt); assertThat(jpaDataStore.getPrivateKeySalt(), equalTo(salt)); }
### Question: JpaDataStore implements DataStore { @Override public boolean saveChannel(final Channel channel) { final JpaOperation<Boolean> saveChannel = new JpaOperation<Boolean>() { @Override public Boolean perform(final EntityManager em) { UserAgentDTO userAgent = em.find(UserAgentDTO.class, channel.getUAID()); if (userAgent == null) { userAgent = new UserAgentDTO(channel.getUAID()); } userAgent.addChannel(channel.getChannelId(), channel.getVersion(), channel.getEndpointToken()); em.merge(userAgent); return Boolean.TRUE; } }; try { return jpaExecutor.execute(saveChannel); } catch (final Exception e) { logger.error("Could not save channel [" + channel.getChannelId() + "]", e); return false; } } JpaDataStore(final String persistenceUnit); @Override void savePrivateKeySalt(final byte[] salt); @Override byte[] getPrivateKeySalt(); @Override boolean saveChannel(final Channel channel); @Override Channel getChannel(final String channelId); @Override void removeChannels(final Set<String> channelIds); @Override Set<String> getChannelIds(final String uaid); @Override void removeChannels(final String uaid); @Override String updateVersion(final String endpointToken, final long version); @Override String saveUnacknowledged(final String channelId, final long version); @Override Set<Ack> getUnacknowledged(final String uaid); @Override Set<Ack> removeAcknowledged(final String uaid, final Set<Ack> acked); }### Answer: @Test public void saveChannel() { final boolean saved = jpaDataStore.saveChannel(newChannel(UUIDUtil.newUAID(), UUID.randomUUID().toString(), 10L)); assertThat(saved, is(true)); } @Test public void saveChannels() { final String uaid = UUIDUtil.newUAID(); final String channelId = UUID.randomUUID().toString(); assertThat(jpaDataStore.saveChannel(newChannel(uaid, channelId, 1L)), is(true)); assertThat(jpaDataStore.saveChannel(newChannel(uaid, channelId, 10L)), is(true)); }
### Question: JpaDataStore implements DataStore { @Override public Set<String> getChannelIds(final String uaid) { final JpaOperation<Set<String>> getChannelIds = new JpaOperation<Set<String>>() { @Override public Set<String> perform(final EntityManager em) { final Set<String> channels = new HashSet<String>(); final UserAgentDTO userAgent = em.find(UserAgentDTO.class, uaid); if (userAgent != null) { for (ChannelDTO dto : userAgent.getChannels()) { channels.add(dto.getChannelId()); } } return channels; } }; return jpaExecutor.execute(getChannelIds); } JpaDataStore(final String persistenceUnit); @Override void savePrivateKeySalt(final byte[] salt); @Override byte[] getPrivateKeySalt(); @Override boolean saveChannel(final Channel channel); @Override Channel getChannel(final String channelId); @Override void removeChannels(final Set<String> channelIds); @Override Set<String> getChannelIds(final String uaid); @Override void removeChannels(final String uaid); @Override String updateVersion(final String endpointToken, final long version); @Override String saveUnacknowledged(final String channelId, final long version); @Override Set<Ack> getUnacknowledged(final String uaid); @Override Set<Ack> removeAcknowledged(final String uaid, final Set<Ack> acked); }### Answer: @Test public void getChannelsForNonExistingUserAgent() throws ChannelNotFoundException { final Set<String> channels = jpaDataStore.getChannelIds(UUIDUtil.newUAID()); assertThat(channels.isEmpty(), is(true)); }
### Question: JpaDataStore implements DataStore { @Override public void removeChannels(final Set<String> channelIds) { if (channelIds == null || channelIds.isEmpty()) { return; } final JpaOperation<Integer> removeChannel = new JpaOperation<Integer>() { @Override public Integer perform(EntityManager em) { final Query delete = em.createQuery("DELETE from ChannelDTO c where c.channelId in (:channelIds)"); delete.setParameter("channelIds", channelIds); return delete.executeUpdate(); } }; jpaExecutor.execute(removeChannel); } JpaDataStore(final String persistenceUnit); @Override void savePrivateKeySalt(final byte[] salt); @Override byte[] getPrivateKeySalt(); @Override boolean saveChannel(final Channel channel); @Override Channel getChannel(final String channelId); @Override void removeChannels(final Set<String> channelIds); @Override Set<String> getChannelIds(final String uaid); @Override void removeChannels(final String uaid); @Override String updateVersion(final String endpointToken, final long version); @Override String saveUnacknowledged(final String channelId, final long version); @Override Set<Ack> getUnacknowledged(final String uaid); @Override Set<Ack> removeAcknowledged(final String uaid, final Set<Ack> acked); }### Answer: @Test public void removeChannels() { final String uaid = UUIDUtil.newUAID(); final String channelId1 = UUID.randomUUID().toString(); final String channelId2 = UUID.randomUUID().toString(); jpaDataStore.saveChannel(newChannel(uaid, channelId1, 10L)); jpaDataStore.saveChannel(newChannel(uaid, channelId2, 10L)); jpaDataStore.removeChannels(uaid); assertThat(channelExists(channelId1, jpaDataStore), is(false)); } @Test public void removeChannelsNoUserAgentStored() { final String channelId1 = UUID.randomUUID().toString(); jpaDataStore.removeChannels(UUIDUtil.newUAID()); assertThat(channelExists(channelId1, jpaDataStore), is(false)); }
### Question: MessageFrame extends DefaultByteBufHolder implements Frame { public List<String> messages() { return Collections.unmodifiableList(messages); } MessageFrame(final String message); MessageFrame(final String... messages); MessageFrame(final List<String> messages); List<String> messages(); @Override MessageFrame copy(); @Override MessageFrame duplicate(); @Override MessageFrame retain(); @Override MessageFrame retain(int increment); @Override String toString(); }### Answer: @Test public void messages() { final MessageFrame messageFrame = new MessageFrame("first", "second", "third"); assertThat(messageFrame.messages(), hasItems("first", "second", "third")); messageFrame.release(); }