method2testcases
stringlengths
118
6.63k
### Question: HttpServerRequestImpl implements HttpServerRequest { @Override public String uri() { if (uri == null) { String path = path().equals("/") ? "" : path(); uri = scheme() + ": if (query().length() > 0) { uri = uri + "?" + query(); }; } return uri; } 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 testUri(TestContext context) { context.assertEquals("http: }
### Question: HttpServerRequestImpl implements HttpServerRequest { @Override public String path() { return request.getString("path"); } 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 testPath(TestContext context) { context.assertEquals("/", request.path()); }
### Question: HttpServerRequestImpl implements HttpServerRequest { @Override public String query() { if (query == null) { StringBuilder queryBuilder = new StringBuilder(); for (Map.Entry<String, String> param : params()) { if (queryBuilder.length() > 0) { queryBuilder.append("&"); } queryBuilder.append(urlEncode(param.getKey())); queryBuilder.append("="); queryBuilder.append(urlEncode(param.getValue())); } query = queryBuilder.toString(); } return query; } 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 testQuery(TestContext context) { context.assertEquals("p1=1&p2=2", request.query()); }
### Question: HttpServerRequestImpl implements HttpServerRequest { @Override public String host() { return localHost; } 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 testHost(TestContext context) { context.assertEquals("localhost", request.host()); }
### Question: HttpServerRequestImpl implements HttpServerRequest { @Override public HttpServerResponse response() { return response; } 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 testResponse(TestContext context) { context.assertEquals(response, request.response()); }
### Question: LambdaServer implements HttpServer { @Override public ReadStream<ServerWebSocket> websocketStream() { return null; } 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 testWebsocketStream(TestContext context) { context.assertNull(server.websocketStream()); }
### Question: HttpServerRequestImpl implements HttpServerRequest { @Override public MultiMap headers() { if (headers == null) { headers = MultiMap.caseInsensitiveMultiMap(); JsonObject requestHeaders = request.getJsonObject("headers"); if (requestHeaders != null) { for (Map.Entry<String, Object> entry : requestHeaders) { headers.add(entry.getKey(), entry.getValue().toString()); } } } return headers; } 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 testHeaders(TestContext context) { context.assertEquals("val1", request.headers().get("X-H1")); }
### Question: HttpServerRequestImpl implements HttpServerRequest { @Override public String getHeader(String headerName) { return headers().get(headerName); } 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 testGetHeader(TestContext context) { context.assertEquals("val1", request.getHeader("X-H1")); }
### Question: HttpServerRequestImpl implements HttpServerRequest { @Override public MultiMap params() { if (params == null) { params = new CaseSensitiveMultiMapImpl(); JsonObject queryParams = request.getJsonObject("queryStringParameters"); if (queryParams != null) { for (Map.Entry<String, Object> entry : queryParams) { params.add(entry.getKey(), entry.getValue().toString()); } } } return params; } 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 testParams(TestContext context) { MultiMap params = request.params(); context.assertEquals(2, params.size()); context.assertEquals("1", params.get("p1")); context.assertEquals("2", params.get("p2")); }
### Question: HttpServerRequestImpl implements HttpServerRequest { @Override public String getParam(String paramName) { return params().get(paramName); } 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 testGetParam(TestContext context) { context.assertEquals("1", request.getParam("p1")); context.assertEquals("2", request.getParam("p2")); }
### Question: HttpServerRequestImpl implements HttpServerRequest { @Override public SocketAddress localAddress() { if (localAddress == null) { localAddress = new SocketAddress() { @Override public String host() { return localHost; } @Override public int port() { return localPort; } }; } return localAddress; } 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 testLocalAddress(TestContext context) { SocketAddress address = request.localAddress(); context.assertEquals("localhost", address.host()); context.assertEquals(8888, address.port()); }
### Question: HttpServerRequestImpl implements HttpServerRequest { @Override public X509Certificate[] peerCertificateChain() throws SSLPeerUnverifiedException { 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 testPeerCertificateChain(TestContext context) throws SSLPeerUnverifiedException { context.assertNull(request.peerCertificateChain()); }
### Question: HttpServerRequestImpl implements HttpServerRequest { @Override public String absoluteURI() { if (absoluteURI == null) { absoluteURI = uri(); } return absoluteURI; } 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 testAbsoluteURI(TestContext context) { context.assertEquals("http: }
### Question: HttpServerRequestImpl implements HttpServerRequest { @Override public NetSocket netSocket() { 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 testNetSocket(TestContext context) { context.assertNull(request.netSocket()); }
### Question: HttpServerRequestImpl implements HttpServerRequest { @Override public HttpServerRequest setExpectMultipart(boolean expect) { checkEnded(); if (expect) { throw new java.lang.UnsupportedOperationException("Not supported yet."); } 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(expected = java.lang.UnsupportedOperationException.class) public void testSetExpectMultipart(TestContext context) { request.setExpectMultipart(true); }
### Question: HttpServerRequestImpl implements HttpServerRequest { @Override public boolean isExpectMultipart() { return false; } 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 testIsExpectMultipart(TestContext context) { context.assertFalse(request.isExpectMultipart()); }
### Question: LambdaServer implements HttpServer { @Override public HttpServer websocketHandler(Handler<ServerWebSocket> handler) { this.websocketHandler = handler; 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 testWebsocketHandler(TestContext context) { Handler<ServerWebSocket> handler = new Handler<ServerWebSocket>() { @Override public void handle(ServerWebSocket event) { } }; context.assertEquals(server, server.websocketHandler(handler)); context.assertEquals(handler, server.websocketHandler()); }
### Question: HttpServerRequestImpl implements HttpServerRequest { @Override public HttpServerRequest uploadHandler(Handler<HttpServerFileUpload> uploadHandler) { checkEnded(); 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 testUploadHandler(TestContext context) { context.assertEquals(request, request.uploadHandler(p -> { })); }
### Question: HttpServerRequestImpl implements HttpServerRequest { @Override public MultiMap formAttributes() { if (attributes == null) { attributes = MultiMap.caseInsensitiveMultiMap(); } return attributes; } 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 testformAttributes(TestContext context) { MultiMap attr = request.formAttributes(); context.assertEquals(0, attr.size()); }
### Question: HttpServerRequestImpl implements HttpServerRequest { @Override public String getFormAttribute(String attributeName) { return formAttributes().get(attributeName); } 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 testGetFormAttribute(TestContext context) { context.assertNull(request.getFormAttribute("X")); }
### Question: HttpServerRequestImpl implements HttpServerRequest { @Override public ServerWebSocket upgrade() { throw new java.lang.UnsupportedOperationException("Not supported yet."); } 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(expected = java.lang.UnsupportedOperationException.class) public void testUpgrade(TestContext context) { request.upgrade(); }
### Question: HttpServerRequestImpl implements HttpServerRequest { @Override public boolean isEnded() { return ended; } 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 testIsEnded(TestContext context) { context.assertFalse(request.isEnded()); request.handleEnd(); context.assertTrue(request.isEnded()); }
### 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: HttpServerResponseImpl implements HttpServerResponse { @Override public boolean writeQueueFull() { checkWritten(); return false; } HttpServerResponseImpl(OutputStream output); @Override boolean writeQueueFull(); @Override HttpServerResponse exceptionHandler(Handler<Throwable> handler); @Override HttpServerResponse setWriteQueueMaxSize(int maxSize); @Override HttpServerResponse drainHandler(Handler<Void> handler); @Override int getStatusCode(); @Override HttpServerResponse setStatusCode(int statusCode); @Override String getStatusMessage(); @Override HttpServerResponse setStatusMessage(String statusMessage); @Override HttpServerResponse setChunked(boolean chunked); @Override boolean isChunked(); @Override MultiMap headers(); @Override HttpServerResponse putHeader(String name, String value); @Override HttpServerResponse putHeader(CharSequence name, CharSequence value); @Override HttpServerResponse putHeader(String name, Iterable<String> values); @Override HttpServerResponse putHeader(CharSequence name, Iterable<CharSequence> values); @Override MultiMap trailers(); @Override HttpServerResponse putTrailer(String name, String value); @Override HttpServerResponse putTrailer(CharSequence name, CharSequence value); @Override HttpServerResponse putTrailer(String name, Iterable<String> values); @Override HttpServerResponse putTrailer(CharSequence name, Iterable<CharSequence> value); @Override HttpServerResponse closeHandler(Handler<Void> handler); @Override HttpServerResponse endHandler(Handler<Void> handler); @Override HttpServerResponse write(String chunk, String enc); @Override HttpServerResponse write(String chunk); @Override HttpServerResponse write(Buffer data); @Override HttpServerResponse writeContinue(); @Override void end(String chunk); @Override void end(String chunk, String enc); @Override void end(Buffer chunk); @Override void end(); @Override HttpServerResponse sendFile(String filename, long offset, long length); @Override HttpServerResponse sendFile(String filename, long offset, long length, Handler<AsyncResult<Void>> resultHandler); @Override void close(); @Override boolean ended(); @Override boolean closed(); @Override boolean headWritten(); @Override HttpServerResponse headersEndHandler(Handler<Void> handler); @Override HttpServerResponse bodyEndHandler(Handler<Void> handler); @Override long bytesWritten(); @Override int streamId(); @Override void reset(long code); @Override HttpServerResponse push(HttpMethod method, String path, MultiMap headers, Handler<AsyncResult<HttpServerResponse>> handler); @Override HttpServerResponse push(io.vertx.core.http.HttpMethod method, String host, String path, Handler<AsyncResult<HttpServerResponse>> handler); @Override HttpServerResponse push(HttpMethod method, String path, Handler<AsyncResult<HttpServerResponse>> handler); @Override HttpServerResponse push(HttpMethod method, String host, String path, MultiMap headers, Handler<AsyncResult<HttpServerResponse>> handler); @Override HttpServerResponse writeCustomFrame(int type, int flags, Buffer payload); }### Answer: @Test public void testWriteQueueFull(TestContext context) { context.assertFalse(response.writeQueueFull()); }
### Question: DeviceTokenValidator implements ConstraintValidator<DeviceTokenCheck, Installation> { public static boolean isValidDeviceTokenForVariant(final String deviceToken, final VariantType type) { switch (type) { case IOS: case IOS_TOKEN: return IOS_DEVICE_TOKEN.matcher(deviceToken).matches(); case ANDROID: return ANDROID_DEVICE_TOKEN.matcher(deviceToken).matches(); case WEB_PUSH: return isWebPushRegistration(deviceToken); } return false; } @Override void initialize(DeviceTokenCheck constraintAnnotation); @Override boolean isValid(Installation installation, ConstraintValidatorContext context); static boolean isValidDeviceTokenForVariant(final String deviceToken, final VariantType type); }### Answer: @Test public void testValidToken() { final VariantType andVariantType = VariantType.ANDROID; assertThat(DeviceTokenValidator.isValidDeviceTokenForVariant("eHlfnI0__dI:APA91bEhtHefML2lr_sBQ-bdXIyEn5owzkZg_p_y7SRyNKRMZ3XuzZhBpTOYIh46tqRYQIc-7RTADk4nM5H-ONgPDWHodQDS24O5GuKP8EZEKwNh4Zxdv1wkZJh7cU2PoLz9gn4Nxqz-", andVariantType)).isTrue(); } @Test public void testEmptyString() { final VariantType andVariantType = VariantType.ANDROID; assertThat(DeviceTokenValidator.isValidDeviceTokenForVariant("", andVariantType)).isFalse(); } @Test public void testInvalidToken() { final VariantType andVariantType = VariantType.ANDROID; assertThat(DeviceTokenValidator.isValidDeviceTokenForVariant("some-bogus:token", andVariantType)).isFalse(); } @Test public void testInvalidWebPush() { final Gson gson = new Gson(); final VariantType webPushType = VariantType.WEB_PUSH; assertThat(DeviceTokenValidator.isValidDeviceTokenForVariant("some-bogus:token", webPushType)).isFalse(); WebPushRegistration registration = new WebPushRegistration(); String registrationJson = Base64.getEncoder().encodeToString(gson.toJson(registration).getBytes()); assertThat(DeviceTokenValidator.isValidDeviceTokenForVariant(registrationJson, webPushType)).isFalse(); registration.setEndpoint("https: registrationJson = gson.toJson(registration); assertThat(DeviceTokenValidator.isValidDeviceTokenForVariant(registrationJson, webPushType)).isFalse(); } @Test public void testValidWebPush() { final Gson gson = new Gson(); final VariantType webPushType = VariantType.WEB_PUSH; WebPushRegistration registration = new WebPushRegistration(); registration.setEndpoint("https: registration.getKeys().setAuth("authTokens"); registration.getKeys().setP256dh("devicePublicKey"); String registrationJson = Base64.getEncoder().encodeToString(gson.toJson(registration).getBytes()); assertThat(DeviceTokenValidator.isValidDeviceTokenForVariant(registrationJson, webPushType)).isTrue(); }
### Question: UnifiedPushMessage implements Serializable { public String toStrippedJsonString() { try { final Map<String, Object> json = new LinkedHashMap<>(); json.put("alert", this.message.getAlert()); json.put("priority", this.message.getPriority().toString()); if (this.getMessage().getBadge()>0) { json.put("badge", Integer.toString(this.getMessage().getBadge())); } json.put("criteria", this.criteria); json.put("config", this.config); return OBJECT_MAPPER.writeValueAsString(json); } catch (JsonProcessingException e) { return "[\"invalid json\"]"; } catch (IOException e) { return "[\"invalid json\"]"; } } Criteria getCriteria(); void setCriteria(Criteria criteria); Config getConfig(); void setConfig(Config config); Message getMessage(); void setMessage(Message message); String toStrippedJsonString(); String toMinimizedJsonString(); String toJsonString(); @Override String toString(); }### Answer: @Test public void testMessageToStrippedJson() throws IOException, URISyntaxException { final Map<String, Object> container = new LinkedHashMap<>(); final Map<String, Object> messageObject = new LinkedHashMap<>(); final Map<String, Object> apnsObject = new LinkedHashMap<>(); messageObject.put("alert", "HELLO!"); messageObject.put("sound", "default"); messageObject.put("badge", 2); Map<String, Object> data = new HashMap<>(); data.put("key", "value"); data.put("key2", "value"); messageObject.put("user-data", data); apnsObject.put("action-category", "category"); apnsObject.put("content-available", "true"); messageObject.put("simple-push", "version=123"); messageObject.put("apns",apnsObject); container.put("message", messageObject); final UnifiedPushMessage unifiedPushMessage = parsePushMessage(container); String json = unifiedPushMessage.toStrippedJsonString(); Path path = Paths.get(getClass().getResource("/message-tostrippedjson.json").toURI()); String expectedJson = new String(Files.readAllBytes(path), Charset.defaultCharset()); assertEquals(expectedJson.replaceAll("\\s", ""), json); } @Test public void testMessageToJson() throws IOException, URISyntaxException { final Map<String, Object> container = new LinkedHashMap<>(); final Map<String, Object> messageObject = new LinkedHashMap<>(); final Map<String, Object> apnsObject = new LinkedHashMap<>(); messageObject.put("alert", "HELLO!"); messageObject.put("sound", "default"); messageObject.put("badge", 2); Map<String, Object> data = new HashMap<>(); data.put("key", "value"); data.put("key2", "value"); messageObject.put("user-data", data); apnsObject.put("action-category", "category"); apnsObject.put("content-available", "true"); messageObject.put("simple-push", "version=123"); messageObject.put("apns",apnsObject); container.put("message", messageObject); final UnifiedPushMessage unifiedPushMessage = parsePushMessage(container); String json = unifiedPushMessage.toStrippedJsonString(); Path path = Paths.get(getClass().getResource("/message-tojson.json").toURI()); String expectedJson = new String(Files.readAllBytes(path), Charset.defaultCharset()); assertEquals(expectedJson.replaceAll("\\s", ""), json); }
### 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: InstallationManagementEndpoint { static LinkHeader getLinkHeader(Integer page, long totalPages, UriInfo uri) { LinkHeader header = new LinkHeader(); if (page != 0) { header.addLink(buildLink("prev", page - 1, uri)); header.addLink(buildLink("first", 0, uri)); } if (page < totalPages) { header.addLink(buildLink("next", page + 1, uri)); header.addLink(buildLink("last", totalPages, uri)); } return header; } @GET @Produces(MediaType.APPLICATION_JSON) Response findInstallations(@PathParam("variantID") String variantId, @QueryParam("page") Integer page, @QueryParam("per_page") Integer pageSize, @QueryParam("search") String search, @Context UriInfo uri); @GET @Path("/{installationID}") @Produces(MediaType.APPLICATION_JSON) Response findInstallation(@PathParam("variantID") String variantId, @PathParam("installationID") String installationId); @PUT @Path("/{installationID}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) Response updateInstallation(Installation entity, @PathParam("variantID") String variantId, @PathParam("installationID") String installationId); @DELETE @Path("/{installationID}") @Produces(MediaType.APPLICATION_JSON) Response removeInstallation(@PathParam("variantID") String variantId, @PathParam("installationID") String installationId); }### Answer: @Test public void shouldGenerateHeaderLinksFirstPage() throws URISyntaxException { final ResteasyUriInfo uriInfo = getUriInfo(); final LinkHeader linkHeader = endpoint.getLinkHeader(0, 3, uriInfo); assertThat(findLinkByRel(linkHeader, "prev")).isNull(); final Link next = findLinkByRel(linkHeader, "next"); assertThat(next).isNotNull(); assertThat(next.getHref()).isEqualTo("/?page=1"); assertThat(findLinkByRel(linkHeader, "first")).isNull(); } @Test public void shouldGenerateHeaderLinksNormalPage() throws URISyntaxException { final ResteasyUriInfo uriInfo = getUriInfo(); final LinkHeader linkHeader = endpoint.getLinkHeader(2, 3, uriInfo); final Link prev = findLinkByRel(linkHeader, "prev"); assertThat(prev).isNotNull(); assertThat(prev.getHref()).isEqualTo("/?page=1"); final Link next = findLinkByRel(linkHeader, "next"); assertThat(next).isNotNull(); assertThat(next.getHref()).isEqualTo("/?page=3"); } @Test public void shouldGenerateHeaderLinksLastPage() throws URISyntaxException { final ResteasyUriInfo uriInfo = getUriInfo(); final LinkHeader linkHeader = endpoint.getLinkHeader(3, 3, uriInfo); final Link prev = findLinkByRel(linkHeader, "prev"); assertThat(prev).isNotNull(); assertThat(prev.getHref()).isEqualTo("/?page=2"); final Link first = findLinkByRel(linkHeader, "first"); assertThat(first).isNotNull(); assertThat(first.getHref()).isEqualTo("/?page=0"); assertThat(findLinkByRel(linkHeader, "last")).isNull(); }
### Question: AndroidVariantEndpoint extends AbstractVariantEndpoint<AndroidVariant> { @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response registerAndroidVariant( AndroidVariant androidVariant, @PathParam("pushAppID") String pushApplicationID, @Context UriInfo uriInfo) { PushApplication pushApp = getSearch().findByPushApplicationIDForDeveloper(pushApplicationID); if (pushApp == null) { return Response.status(Status.NOT_FOUND).entity(ErrorBuilder.forPushApplications().notFound().build()).build(); } try { validateModelClass(androidVariant); } catch (ConstraintViolationException cve) { logger.trace("Unable to create Android variant"); ResponseBuilder builder = createBadRequestResponse(cve.getConstraintViolations()); return builder.build(); } logger.trace("Register Android variant with Push Application '{}'", pushApplicationID); variantService.addVariant(androidVariant); pushAppService.addVariant(pushApp, androidVariant); return Response.created(uriInfo.getAbsolutePathBuilder().path(String.valueOf(androidVariant.getVariantID())).build()).entity(androidVariant).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 shouldRegisterAndroidVariantSuccessfully() { final AndroidVariant variant = new AndroidVariant(); final ResteasyUriInfo uriInfo = new ResteasyUriInfo("http: final PushApplication pushApp = new PushApplication(); when(searchService.findByPushApplicationIDForDeveloper("push-app-id")).thenReturn(pushApp); when(validator.validate(variant)).thenReturn(Collections.EMPTY_SET); final Response response = this.endpoint.registerAndroidVariant(variant, "push-app-id", uriInfo); assertEquals(response.getStatus(), 201); assertTrue(response.getEntity() == variant); assertEquals(response.getMetadata().get("location").get(0).toString(), "http: verify(variantService).addVariant(variant); verify(pushAppService).addVariant(pushApp, variant); } @Test public void registerAndroidVariantShouldReturn404WhenPushAppDoesNotExist() { final AndroidVariant variant = new AndroidVariant(); final ResteasyUriInfo uriInfo = new ResteasyUriInfo("http: final PushApplication pushApp = new PushApplication(); when(searchService.findByPushApplicationIDForDeveloper("push-app-id")).thenReturn(null); final Response response = this.endpoint.registerAndroidVariant(variant, "push-app-id", uriInfo); assertEquals(response.getStatus(), 404); verify(variantService, never()).addVariant(any()); verify(validator, never()).validate(any()); verify(pushAppService, never()).addVariant(any(), any()); } @Test public void registerAndroidVariantShouldReturn400WhenVariantModelIsNotValid() { final AndroidVariant variant = new AndroidVariant(); final ResteasyUriInfo uriInfo = new ResteasyUriInfo("http: final PushApplication pushApp = new PushApplication(); when(searchService.findByPushApplicationIDForDeveloper("push-app-id")).thenReturn(pushApp); when(validator.validate(variant)).thenReturn(Sets.newHashSet(sampleViolation)); final Response response = this.endpoint.registerAndroidVariant(variant, "push-app-id", uriInfo); assertEquals(response.getStatus(), 400); verify(variantService, never()).addVariant(variant); verify(pushAppService, never()).addVariant(pushApp, variant); }
### 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: AndroidVariantEndpoint extends AbstractVariantEndpoint<AndroidVariant> { @PUT @Path("/{androidID}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response updateAndroidVariant( @PathParam("pushAppID") String pushApplicationId, @PathParam("androidID") String androidID, AndroidVariant updatedAndroidApplication) { final PushApplication application = getSearch().findByPushApplicationIDForDeveloper(pushApplicationId); if (application == null) { return Response.status(Response.Status.NOT_FOUND).entity(ErrorBuilder.forPushApplications().notFound().build()).build(); } var variant = variantService.findByVariantID(androidID); if (variant != null) { if (!(variant instanceof AndroidVariant)) { return Response.status(Response.Status.NOT_FOUND).entity(ErrorBuilder.forVariants().notFound().build()).build(); } AndroidVariant androidVariant = (AndroidVariant) variant; try { updatedAndroidApplication.merge(androidVariant); validateModelClass(androidVariant); } catch (ConstraintViolationException cve) { logger.info("Unable to update Android Variant '{}'", androidVariant.getVariantID()); logger.debug("Details: {}", cve); ResponseBuilder builder = createBadRequestResponse(cve.getConstraintViolations()); return builder.build(); } logger.trace("Updating Android Variant '{}'", androidID); variantService.updateVariant(androidVariant); return Response.ok(androidVariant).build(); } return Response.status(Status.NOT_FOUND).entity(ErrorBuilder.forVariants().notFound().build()).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 shouldUpdateAndroidVariantSuccessfully() { final AndroidVariant originalVariant = new AndroidVariant(); final AndroidVariant updatedVariant = new AndroidVariant(); final PushApplication pushApp = new PushApplication(); originalVariant.setGoogleKey("Original Google Key"); updatedVariant.setGoogleKey("Updated Google Key"); when(searchService.findByPushApplicationIDForDeveloper("push-app-id")).thenReturn(pushApp); when(variantService.findByVariantID("variant-id")).thenReturn(originalVariant); when(validator.validate(updatedVariant)).thenReturn(Collections.EMPTY_SET); final Response response = this.endpoint.updateAndroidVariant("push-app-id", "variant-id", updatedVariant); assertEquals(200,response.getStatus()); assertTrue(response.getEntity() == originalVariant); assertEquals(originalVariant.getGoogleKey(), "Updated Google Key"); verify(variantService).updateVariant(originalVariant); }
### Question: WebPushVariantEndpoint extends AbstractVariantEndpoint<WebPushVariant> { @GET @Produces(MediaType.APPLICATION_JSON) public Response listAllWebPushVariationsForPushApp(@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(); } WebPushVariantEndpoint(); WebPushVariantEndpoint(Validator validator, SearchManager searchManager); @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) Response registerWebPushVariant( WebPushVariant webPushVariant, @PathParam("pushAppID") String pushApplicationID, @Context UriInfo uriInfo); @GET @Produces(MediaType.APPLICATION_JSON) Response listAllWebPushVariationsForPushApp(@PathParam("pushAppID") String pushApplicationID); @PUT @Path("/{webPushID}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) Response updateWebPushVariant(@PathParam("pushAppID") String pushApplicationID, @PathParam("webPushID") String webPushID, WebPushVariant updatedVariant); @PUT @Path("/{variantId}/renew") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) Response renewKeys(@PathParam("pushAppID") String pushApplicationID, @PathParam("variantId") String variantId); }### Answer: @Test public void shouldListAllAndroidVariationsForPushAppSuccessfully() { final WebPushVariant webPushVariant = new WebPushVariant(); final Variant iOSVariant = new iOSVariant(); final PushApplication pushApp = new PushApplication(); pushApp.setVariants(Lists.newArrayList(webPushVariant, iOSVariant)); when(searchService.findByPushApplicationIDForDeveloper("push-app-id")).thenReturn(pushApp); final Response response = this.endpoint.listAllWebPushVariationsForPushApp("push-app-id"); assertEquals(response.getStatus(), 200); assertTrue(((Collection) response.getEntity()).iterator().next() == webPushVariant); }
### Question: WebPushVariantEndpoint extends AbstractVariantEndpoint<WebPushVariant> { @PUT @Path("/{webPushID}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response updateWebPushVariant(@PathParam("pushAppID") String pushApplicationID, @PathParam("webPushID") String webPushID, WebPushVariant updatedVariant) { final PushApplication application = getSearch().findByPushApplicationIDForDeveloper(pushApplicationID); if (application == null) { return Response.status(Response.Status.NOT_FOUND).entity(ErrorBuilder.forPushApplications().notFound().build()).build(); } var variant = variantService.findByVariantID(webPushID); if (variant != null) { if (!(variant instanceof WebPushVariant)) { return Response.status(Response.Status.NOT_FOUND).entity(ErrorBuilder.forVariants().notFound().build()).build(); } WebPushVariant webPushVariant = (WebPushVariant) variant; try { updatedVariant.merge(webPushVariant); validateModelClass(webPushVariant); } catch (ConstraintViolationException cve) { logger.info("Unable to update WebPush Variant '{}'", webPushVariant.getVariantID()); logger.debug("Details: {}", cve); Response.ResponseBuilder builder = createBadRequestResponse(cve.getConstraintViolations()); return builder.build(); } logger.trace("Updating WebPush Variant '{}'", webPushID); variantService.updateVariant(webPushVariant); return Response.ok(webPushVariant).build(); } return Response.status(Response.Status.NOT_FOUND).entity(ErrorBuilder.forVariants().notFound().build()).build(); } WebPushVariantEndpoint(); WebPushVariantEndpoint(Validator validator, SearchManager searchManager); @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) Response registerWebPushVariant( WebPushVariant webPushVariant, @PathParam("pushAppID") String pushApplicationID, @Context UriInfo uriInfo); @GET @Produces(MediaType.APPLICATION_JSON) Response listAllWebPushVariationsForPushApp(@PathParam("pushAppID") String pushApplicationID); @PUT @Path("/{webPushID}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) Response updateWebPushVariant(@PathParam("pushAppID") String pushApplicationID, @PathParam("webPushID") String webPushID, WebPushVariant updatedVariant); @PUT @Path("/{variantId}/renew") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) Response renewKeys(@PathParam("pushAppID") String pushApplicationID, @PathParam("variantId") String variantId); }### Answer: @Test public void shouldUpdateWebPushVariantSuccessfully() { final WebPushVariant originalVariant = new WebPushVariant(); final WebPushVariant updatedVariant = new WebPushVariant(); final PushApplication pushApp = new PushApplication(); originalVariant.setPublicKey("test public Key"); updatedVariant.setPublicKey("update public Key"); when(searchService.findByPushApplicationIDForDeveloper("push-app-id")).thenReturn(pushApp); when(variantService.findByVariantID("variant-id")).thenReturn(originalVariant); when(validator.validate(updatedVariant)).thenReturn(Collections.EMPTY_SET); final Response response = this.endpoint.updateWebPushVariant("push-app-id", "variant-id", updatedVariant); assertEquals(response.getStatus(), 200); assertTrue(response.getEntity() == originalVariant); assertEquals(originalVariant.getPublicKey(), "update public Key"); verify(variantService).updateVariant(originalVariant); }
### Question: iOSTokenVariantEndpoint extends AbstractVariantEndpoint<iOSTokenVariant> { @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response registeriOSVariant( iOSTokenVariant iOSVariant, @PathParam("pushAppID") String pushApplicationID, @Context UriInfo uriInfo) { PushApplication pushApp = getSearch().findByPushApplicationIDForDeveloper(pushApplicationID); if (pushApp == null) { return Response.status(Status.NOT_FOUND).entity(ErrorBuilder.forPushApplications().notFound().build()).build(); } try { validateModelClass(iOSVariant); } catch (ConstraintViolationException cve) { logger.trace("Unable to create iOS variant entity"); ResponseBuilder builder = createBadRequestResponse(cve.getConstraintViolations()); return builder.build(); } logger.trace("Register iOS token variant with Push Application '{}'", pushApplicationID); variantService.addVariant(iOSVariant); pushAppService.addVariant(pushApp, iOSVariant); return Response.created(uriInfo.getAbsolutePathBuilder().path(String.valueOf(iOSVariant.getVariantID())).build()).entity(iOSVariant).build(); } iOSTokenVariantEndpoint(); iOSTokenVariantEndpoint(Validator validator, SearchManager searchManager); @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) Response registeriOSVariant( iOSTokenVariant iOSVariant, @PathParam("pushAppID") String pushApplicationID, @Context UriInfo uriInfo); @GET @Produces(MediaType.APPLICATION_JSON) Response listAlliOSVariantsForPushApp(@PathParam("pushAppID") String pushApplicationID); @PATCH @Path("/{iOSID}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) Response updateiOSVariant( @PathParam("pushAppID") String pushApplicationId, @PathParam("iOSID") String iOSID, iOSTokenVariant updatediOSVariant); @PUT @Path("/{iOSID}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) Response updateiOSVariant( iOSTokenVariant updatediOSVariant, @PathParam("pushAppID") String pushApplicationId, @PathParam("iOSID") String iOSID); }### Answer: @Test public void shouldRegisteriOSTokenVariantSuccessfully() { final ResteasyUriInfo uriInfo = new ResteasyUriInfo("http: final PushApplication pushApp = new PushApplication(); final iOSTokenVariant form = new iOSTokenVariant(); form.setName("variant name"); form.setPrivateKey("privateKey"); form.setTeamId("team id"); form.setKeyId("key id"); form.setBundleId("test.my.toe"); form.setProduction(false); when(searchService.findByPushApplicationIDForDeveloper("push-app-id")).thenReturn(pushApp); when(validator.validate(form)).thenReturn(Collections.EMPTY_SET); final Response response = this.endpoint.registeriOSVariant(form, "push-app-id", uriInfo); assertEquals(response.getStatus(), 201); final iOSTokenVariant createdVariant = (iOSTokenVariant) response.getEntity(); assertEquals(createdVariant.getName(), "variant name"); assertEquals(createdVariant.getPrivateKey(), "privateKey"); assertEquals(createdVariant.getTeamId(), "team id"); assertEquals(createdVariant.getKeyId(), "key id"); assertEquals(createdVariant.getBundleId(), "test.my.toe"); assertEquals(response.getMetadata().get("location").get(0).toString(), "http: verify(variantService).addVariant(createdVariant); verify(pushAppService).addVariant(pushApp, createdVariant); }
### 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: HttpBasicHelper { public static String[] extractUsernameAndPasswordFromBasicHeader(final HttpServletRequest request) { String username = ""; String password = ""; final String authorizationHeader = getAuthorizationHeader(request); if (authorizationHeader != null && isBasic(authorizationHeader)) { final String base64Token = authorizationHeader.substring(HTTP_BASIC_SCHEME.length()); final String token = new String(Base64.getDecoder().decode(base64Token), StandardCharsets.UTF_8); final int delimiter = token.indexOf(':'); if (delimiter != -1) { username = token.substring(0, delimiter); password = token.substring(delimiter + 1); } } return new String[] { username, password }; } private HttpBasicHelper(); static String[] extractUsernameAndPasswordFromBasicHeader(final HttpServletRequest request); }### Answer: @Test public void extractUsernameAndPasswordFromBasicHeader() { final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); final String encodedUserPassword = Base64.getEncoder().encodeToString("user:password".getBytes(StandardCharsets.UTF_8)); Mockito.when(request.getHeader("Authorization")).thenReturn("Basic " + encodedUserPassword); final String[] credentials = HttpBasicHelper.extractUsernameAndPasswordFromBasicHeader(request); assertThat(credentials).isNotNull(); assertThat(credentials[0]).isEqualTo("user"); assertThat(credentials[1]).isEqualTo("password"); assertThat(credentials[0]).isNotEqualTo(" user"); assertThat(credentials[1]).isNotEqualTo(" password"); } @Test public void tryToExtractUsernameAndPasswordFromEmptyHeader() { final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); Mockito.when(request.getHeader("Authorization")).thenReturn(""); final String[] credentials = HttpBasicHelper.extractUsernameAndPasswordFromBasicHeader(request); assertThat(credentials).isNotNull(); assertThat(credentials[0]).isEqualTo(""); assertThat(credentials[1]).isEqualTo(""); } @Test public void tryToExtractUsernameAndPasswordFromNullHeader() { final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); Mockito.when(request.getHeader("Authorization")).thenReturn(null); final String[] credentials = HttpBasicHelper.extractUsernameAndPasswordFromBasicHeader(request); assertThat(credentials).isNotNull(); assertThat(credentials[0]).isEqualTo(""); assertThat(credentials[1]).isEqualTo(""); }
### 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: NotificationRouter { @TransactionAttribute(TransactionAttributeType.REQUIRED) public void submit(PushApplication pushApplication, InternalUnifiedPushMessage message) { logger.debug("Processing send request with '{}' payload", message.getMessage()); final VariantMap variants = new VariantMap(); final List<String> variantIDs = message.getCriteria().getVariants(); if (variantIDs != null) { variantIDs.forEach(variantID -> { Variant variant = genericVariantService.get().findByVariantID(variantID); if (variant != null) { variants.add(variant); } }); } else { variants.addAll(pushApplication.getVariants()); } String jsonMessageContent = message.toStrippedJsonString() ; if (jsonMessageContent != null && jsonMessageContent.length() >= 4500) { jsonMessageContent = message.toMinimizedJsonString(); } final FlatPushMessageInformation pushMessageInformation = metricsService.storeNewRequestFrom( pushApplication.getPushApplicationID(), jsonMessageContent, message.getIpAddress(), message.getClientIdentifier() ); variants.forEach((variantType, variant) -> { logger.info(String.format("Internal dispatching of push message for one %s variant (by %s)", variantType.getTypeName(), message.getClientIdentifier())); dispatchVariantMessageEvent.fire(new MessageHolderWithVariants(pushMessageInformation, message, variantType, variant)); }); } @TransactionAttribute(TransactionAttributeType.REQUIRED) void submit(PushApplication pushApplication, InternalUnifiedPushMessage message); }### Answer: @Test public void testNoVariants() { countDownLatch = new CountDownLatch(1); assertTrue("variants are empty", app.getVariants().isEmpty()); router.submit(app, message); assertEquals(variants(), variantTypeHolder.getVariantTypes()); } @Test public void testTwoVariantsOfSameType() throws InterruptedException { countDownLatch = new CountDownLatch(1); app.getVariants().add(new AndroidVariant()); app.getVariants().add(new AndroidVariant()); router.submit(app, message); countDownLatch.await(3, TimeUnit.SECONDS); assertEquals(variants(VariantType.ANDROID), variantTypeHolder.getVariantTypes()); } @Test public void testThreeVariantsOfDifferentType() throws InterruptedException { countDownLatch = new CountDownLatch(3); app.getVariants().add(new AndroidVariant()); app.getVariants().add(new iOSVariant()); router.submit(app, message); countDownLatch.await(3, TimeUnit.SECONDS); assertEquals(variants(VariantType.ANDROID, VariantType.IOS), variantTypeHolder.getVariantTypes()); } @Test public void testInvokesMetricsService(FlatPushMessageInformationDao pushMessageInformationDao) { router.submit(app, message); verify(pushMessageInformationDao).create(Mockito.any(FlatPushMessageInformation.class)); } @Test public void testVariantIDsSpecified(GenericVariantService genericVariantService) throws InterruptedException { countDownLatch = new CountDownLatch(2); iOSVariant iOSVariant = new iOSVariant(); iOSVariant.setId("id-ios-variant"); AndroidVariant androidVariant = new AndroidVariant(); androidVariant.setId("id-android-variant"); app.getVariants().addAll(Arrays.asList(iOSVariant, androidVariant)); message.getCriteria().setVariants(Arrays.asList("id-ios-variant", "id-android-variant")); when(genericVariantService.findByVariantID("id-ios-variant")).thenReturn(iOSVariant); when(genericVariantService.findByVariantID("id-android-variant")).thenReturn(androidVariant); router.submit(app, message); countDownLatch.await(3, TimeUnit.SECONDS); assertEquals(variants(VariantType.ANDROID, VariantType.IOS), variantTypeHolder.getVariantTypes()); }
### 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: MapProcessor extends MRTask implements LogicalIOProcessor { public MapProcessor(){ super(true); } MapProcessor(); @Override void initialize(TezProcessorContext processorContext); @Override void handleEvents(List<Event> processorEvents); void close(); @Override void run(Map<String, LogicalInput> inputs, Map<String, LogicalOutput> outputs); @Override void localizeConfiguration(JobConf jobConf); }### Answer: @Test public void testMapProcessor() throws Exception { String dagName = "mrdag0"; String vertexName = MultiStageMRConfigUtil.getInitialMapVertexName(); JobConf jobConf = new JobConf(defaultConf); setUpJobConf(jobConf); MRHelpers.translateVertexConfToTez(jobConf); jobConf.setInt(MRJobConfig.APPLICATION_ATTEMPT_ID, 0); jobConf.setBoolean(MRJobConfig.MR_TEZ_SPLITS_VIA_EVENTS, false); jobConf.set(MRFrameworkConfigs.TASK_LOCAL_RESOURCE_DIR, new Path(workDir, "localized-resources").toUri().toString()); Path mapInput = new Path(workDir, "map0"); MapUtils.generateInputSplit(localFs, workDir, jobConf, mapInput); InputSpec mapInputSpec = new InputSpec("NullSrcVertex", new InputDescriptor(MRInputLegacy.class.getName()) .setUserPayload(MRHelpers.createMRInputPayload(jobConf, null)), 1); OutputSpec mapOutputSpec = new OutputSpec("NullDestVertex", new OutputDescriptor(LocalOnFileSorterOutput.class.getName()) .setUserPayload(TezUtils.createUserPayloadFromConf(jobConf)), 1); LogicalIOProcessorRuntimeTask task = MapUtils.createLogicalTask(localFs, workDir, jobConf, 0, new Path(workDir, "map0"), new TestUmbilical(), dagName, vertexName, Collections.singletonList(mapInputSpec), Collections.singletonList(mapOutputSpec)); task.initialize(); task.run(); task.close(); TezInputContext inputContext = task.getInputContexts().iterator().next(); TezTaskOutput mapOutputs = new TezLocalTaskOutputFiles(jobConf, inputContext.getUniqueIdentifier()); Path mapOutputFile = mapOutputs.getInputFile(new InputAttemptIdentifier(0, 0)); LOG.info("mapOutputFile = " + mapOutputFile); IFile.Reader reader = new IFile.Reader(localFs, mapOutputFile, null, null, null, false, 0, -1); LongWritable key = new LongWritable(); Text value = new Text(); DataInputBuffer keyBuf = new DataInputBuffer(); DataInputBuffer valueBuf = new DataInputBuffer(); long prev = Long.MIN_VALUE; while (reader.nextRawKey(keyBuf)) { reader.nextRawValue(valueBuf); key.readFields(keyBuf); value.readFields(valueBuf); if (prev != Long.MIN_VALUE) { assert(prev <= key.get()); prev = key.get(); } LOG.info("key = " + key.get() + "; value = " + value); } reader.close(); }
### Question: SimpleFetchedInputAllocator implements FetchedInputAllocator, FetchedInputCallback { @Override public synchronized FetchedInput allocate(long actualSize, long compressedSize, InputAttemptIdentifier inputAttemptIdentifier) throws IOException { if (actualSize > maxSingleShuffleLimit || this.usedMemory + actualSize > this.memoryLimit) { return new DiskFetchedInput(actualSize, compressedSize, inputAttemptIdentifier, this, conf, localDirAllocator, fileNameAllocator); } else { this.usedMemory += actualSize; LOG.info("Used memory after allocating " + actualSize + " : " + usedMemory); return new MemoryFetchedInput(actualSize, compressedSize, inputAttemptIdentifier, this); } } SimpleFetchedInputAllocator(String uniqueIdentifier, Configuration conf, long maxTaskAvailableMemory, long memoryAvailable); @Private static long getInitialMemoryReq(Configuration conf, long maxAvailableTaskMemory); @Override synchronized FetchedInput allocate(long actualSize, long compressedSize, InputAttemptIdentifier inputAttemptIdentifier); @Override synchronized void fetchComplete(FetchedInput fetchedInput); @Override synchronized void fetchFailed(FetchedInput fetchedInput); @Override synchronized void freeResources(FetchedInput fetchedInput); }### Answer: @Test public void testInMemAllocation() throws IOException { String localDirs = "/tmp/" + this.getClass().getName(); Configuration conf = new Configuration(); long jvmMax = Runtime.getRuntime().maxMemory(); LOG.info("jvmMax: " + jvmMax); float bufferPercent = 0.1f; conf.setFloat(TezJobConfig.TEZ_RUNTIME_SHUFFLE_INPUT_BUFFER_PERCENT, bufferPercent); conf.setFloat(TezJobConfig.TEZ_RUNTIME_SHUFFLE_MEMORY_LIMIT_PERCENT, 1.0f); conf.setStrings(TezRuntimeFrameworkConfigs.LOCAL_DIRS, localDirs); long inMemThreshold = (long) (bufferPercent * jvmMax); LOG.info("InMemThreshold: " + inMemThreshold); SimpleFetchedInputAllocator inputManager = new SimpleFetchedInputAllocator(UUID.randomUUID().toString(), conf, Runtime.getRuntime().maxMemory(), inMemThreshold); long requestSize = (long) (0.4f * inMemThreshold); long compressedSize = 1l; LOG.info("RequestSize: " + requestSize); FetchedInput fi1 = inputManager.allocate(requestSize, compressedSize, new InputAttemptIdentifier(1, 1)); assertEquals(FetchedInput.Type.MEMORY, fi1.getType()); FetchedInput fi2 = inputManager.allocate(requestSize, compressedSize, new InputAttemptIdentifier(2, 1)); assertEquals(FetchedInput.Type.MEMORY, fi2.getType()); FetchedInput fi3 = inputManager.allocate(requestSize, compressedSize, new InputAttemptIdentifier(3, 1)); assertEquals(FetchedInput.Type.DISK, fi3.getType()); fi1.abort(); fi1.free(); FetchedInput fi4 = inputManager.allocate(requestSize, compressedSize, new InputAttemptIdentifier(4, 1)); assertEquals(FetchedInput.Type.MEMORY, fi4.getType()); fi3.abort(); fi3.free(); FetchedInput fi5 = inputManager.allocate(requestSize, compressedSize, new InputAttemptIdentifier(4, 1)); assertEquals(FetchedInput.Type.DISK, fi5.getType()); }
### Question: ShuffleInputEventHandlerImpl implements ShuffleEventHandler { @Override public void handleEvents(List<Event> events) throws IOException { for (Event event : events) { handleEvent(event); } } ShuffleInputEventHandlerImpl(TezInputContext inputContext, ShuffleManager shuffleManager, FetchedInputAllocator inputAllocator, CompressionCodec codec, boolean ifileReadAhead, int ifileReadAheadLength); @Override void handleEvents(List<Event> events); }### Answer: @Test public void testSimple() throws IOException { TezInputContext inputContext = mock(TezInputContext.class); ShuffleManager shuffleManager = mock(ShuffleManager.class); FetchedInputAllocator inputAllocator = mock(FetchedInputAllocator.class); ShuffleInputEventHandlerImpl handler = new ShuffleInputEventHandlerImpl(inputContext, shuffleManager, inputAllocator, null, false, 0); int taskIndex = 1; Event dme = createDataMovementEvent(0, taskIndex, null); List<Event> eventList = new LinkedList<Event>(); eventList.add(dme); handler.handleEvents(eventList); InputAttemptIdentifier expectedIdentifier = new InputAttemptIdentifier(taskIndex, 0, PATH_COMPONENT); verify(shuffleManager).addKnownInput(eq(HOST), eq(PORT), eq(expectedIdentifier), eq(0)); } @Test public void testCurrentPartitionEmpty() throws IOException { TezInputContext inputContext = mock(TezInputContext.class); ShuffleManager shuffleManager = mock(ShuffleManager.class); FetchedInputAllocator inputAllocator = mock(FetchedInputAllocator.class); ShuffleInputEventHandlerImpl handler = new ShuffleInputEventHandlerImpl(inputContext, shuffleManager, inputAllocator, null, false, 0); int taskIndex = 1; Event dme = createDataMovementEvent(0, taskIndex, createEmptyPartitionByteString(0)); List<Event> eventList = new LinkedList<Event>(); eventList.add(dme); handler.handleEvents(eventList); InputAttemptIdentifier expectedIdentifier = new InputAttemptIdentifier(taskIndex, 0); verify(shuffleManager).addCompletedInputWithNoData(eq(expectedIdentifier)); } @Test public void testOtherPartitionEmpty() throws IOException { TezInputContext inputContext = mock(TezInputContext.class); ShuffleManager shuffleManager = mock(ShuffleManager.class); FetchedInputAllocator inputAllocator = mock(FetchedInputAllocator.class); ShuffleInputEventHandlerImpl handler = new ShuffleInputEventHandlerImpl(inputContext, shuffleManager, inputAllocator, null, false, 0); int taskIndex = 1; Event dme = createDataMovementEvent(0, taskIndex, createEmptyPartitionByteString(1)); List<Event> eventList = new LinkedList<Event>(); eventList.add(dme); handler.handleEvents(eventList); InputAttemptIdentifier expectedIdentifier = new InputAttemptIdentifier(taskIndex, 0, PATH_COMPONENT); verify(shuffleManager).addKnownInput(eq(HOST), eq(PORT), eq(expectedIdentifier), eq(0)); } @Test public void testMultipleEvents1() throws IOException { TezInputContext inputContext = mock(TezInputContext.class); ShuffleManager shuffleManager = mock(ShuffleManager.class); FetchedInputAllocator inputAllocator = mock(FetchedInputAllocator.class); ShuffleInputEventHandlerImpl handler = new ShuffleInputEventHandlerImpl(inputContext, shuffleManager, inputAllocator, null, false, 0); int taskIndex1 = 1; Event dme1 = createDataMovementEvent(0, taskIndex1, createEmptyPartitionByteString(0)); int taskIndex2 = 2; Event dme2 = createDataMovementEvent(0, taskIndex2, null); List<Event> eventList = new LinkedList<Event>(); eventList.add(dme1); eventList.add(dme2); handler.handleEvents(eventList); InputAttemptIdentifier expectedIdentifier1 = new InputAttemptIdentifier(taskIndex1, 0); InputAttemptIdentifier expectedIdentifier2 = new InputAttemptIdentifier(taskIndex2, 0, PATH_COMPONENT); verify(shuffleManager).addCompletedInputWithNoData(eq(expectedIdentifier1)); verify(shuffleManager).addKnownInput(eq(HOST), eq(PORT), eq(expectedIdentifier2), eq(0)); }
### 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: TokenCache { @InterfaceAudience.Private public static void mergeBinaryTokens(Credentials creds, Configuration conf, String tokenFilePath) throws IOException { if (tokenFilePath == null || tokenFilePath.isEmpty()) { throw new RuntimeException("Invalid file path provided" + ", tokenFilePath=" + tokenFilePath); } LOG.info("Merging additional tokens from binary file" + ", binaryFileName=" + tokenFilePath); Credentials binary = Credentials.readTokenStorageFile( new Path("file: creds.mergeAll(binary); } static byte[] getSecretKey(Credentials credentials, Text alias); static void obtainTokensForFileSystems(Credentials credentials, Path[] ps, Configuration conf); @InterfaceAudience.Private static void setSessionToken(Token<? extends TokenIdentifier> t, Credentials credentials); @SuppressWarnings("unchecked") @InterfaceAudience.Private static Token<JobTokenIdentifier> getSessionToken(Credentials credentials); @InterfaceAudience.Private static void mergeBinaryTokens(Credentials creds, Configuration conf, String tokenFilePath); }### Answer: @Test @SuppressWarnings("deprecation") public void testBinaryCredentials() throws Exception { String binaryTokenFile = null; try { Path TEST_ROOT_DIR = new Path("target"); binaryTokenFile = FileSystem.getLocal(conf).makeQualified( new Path(TEST_ROOT_DIR, "tokenFile")).toUri().getPath(); MockFileSystem fs1 = createFileSystemForServiceName("service1"); MockFileSystem fs2 = createFileSystemForServiceName("service2"); MockFileSystem fs3 = createFileSystemForServiceName("service3"); Credentials creds = new Credentials(); Token<?> token1 = fs1.getDelegationToken(renewer); Token<?> token2 = fs2.getDelegationToken(renewer); creds.addToken(token1.getService(), token1); creds.addToken(token2.getService(), token2); creds.writeTokenStorageFile(new Path(binaryTokenFile), conf); Credentials newCreds = new Credentials(); TokenCache.mergeBinaryTokens(newCreds, conf, binaryTokenFile); Assert.assertTrue(newCreds.getAllTokens().size() > 0); checkTokens(creds, newCreds); } finally { if (binaryTokenFile != null) { try { FileSystem.getLocal(conf).delete(new Path(binaryTokenFile)); } catch (IOException e) { } } } }
### Question: TezCommonUtils { public static Path getTezBaseStagingPath(Configuration conf) { String stagingDirStr = conf.get(TezConfiguration.TEZ_AM_STAGING_DIR, TezConfiguration.TEZ_AM_STAGING_DIR_DEFAULT); Path baseStagingDir; try { Path p = new Path(stagingDirStr); FileSystem fs = p.getFileSystem(conf); if (!fs.exists(p)) { mkDirForAM(fs, p); LOG.info("Stage directory " + p + " doesn't exist and is created"); } baseStagingDir = fs.resolvePath(p); } catch (IOException e) { throw new TezUncheckedException(e); } return baseStagingDir; } static Path getTezBaseStagingPath(Configuration conf); @Private static Path createTezSystemStagingPath(Configuration conf, String strAppId); @Private static Path getTezSystemStagingPath(Configuration conf, String strAppId); @Private static Path getTezConfStagingPath(Path tezSysStagingPath); @Private static Path getTezSessionJarStagingPath(Path tezSysStagingPath); @Private static Path getTezBinPlanStagingPath(Path tezSysStagingPath); @Private static Path getTezTextPlanStagingPath(Path tezSysStagingPath); @Private static Path getRecoveryPath(Path tezSysStagingPath, Configuration conf); @Private static Path getAttemptRecoveryPath(Path recoveryPath, int attemptID); @Private static Path getDAGRecoveryPath(Path attemptRecoverPath, String dagID); @Private static Path getSummaryRecoveryPath(Path attemptRecoverPath); static void mkDirForAM(FileSystem fs, Path dir); static FSDataOutputStream createFileForAM(FileSystem fs, Path filePath); @Private static ByteString compressByteArrayToByteString(byte[] inBytes); @Private static byte[] decompressByteStringToByteArray(ByteString byteString); static final FsPermission TEZ_AM_DIR_PERMISSION; static final FsPermission TEZ_AM_FILE_PERMISSION; static final String TEZ_SYSTEM_SUB_DIR; }### Answer: @Test public void testTezBaseStagingPath() throws Exception { Configuration localConf = new Configuration(); localConf.unset(TezConfiguration.TEZ_AM_STAGING_DIR); localConf.set("fs.defaultFS", "file: Path stageDir = TezCommonUtils.getTezBaseStagingPath(localConf); Assert.assertEquals(stageDir.toString(), "file:" + TezConfiguration.TEZ_AM_STAGING_DIR_DEFAULT); conf.set(TezConfiguration.TEZ_AM_STAGING_DIR, STAGE_DIR); stageDir = TezCommonUtils.getTezBaseStagingPath(conf); Assert.assertEquals(stageDir.toString(), RESOLVED_STAGE_DIR); }
### Question: TezCommonUtils { @Private public static Path createTezSystemStagingPath(Configuration conf, String strAppId) { Path baseStagingPath = getTezBaseStagingPath(conf); Path tezStagingDir; try { tezStagingDir = new Path(baseStagingPath, TEZ_SYSTEM_SUB_DIR); FileSystem fs = tezStagingDir.getFileSystem(conf); tezStagingDir = new Path(tezStagingDir, strAppId); if (!fs.exists(tezStagingDir)) { mkDirForAM(fs, tezStagingDir); LOG.info("Tez system stage directory " + tezStagingDir + " doesn't exist and is created"); } } catch (IOException e) { throw new TezUncheckedException(e); } return tezStagingDir; } static Path getTezBaseStagingPath(Configuration conf); @Private static Path createTezSystemStagingPath(Configuration conf, String strAppId); @Private static Path getTezSystemStagingPath(Configuration conf, String strAppId); @Private static Path getTezConfStagingPath(Path tezSysStagingPath); @Private static Path getTezSessionJarStagingPath(Path tezSysStagingPath); @Private static Path getTezBinPlanStagingPath(Path tezSysStagingPath); @Private static Path getTezTextPlanStagingPath(Path tezSysStagingPath); @Private static Path getRecoveryPath(Path tezSysStagingPath, Configuration conf); @Private static Path getAttemptRecoveryPath(Path recoveryPath, int attemptID); @Private static Path getDAGRecoveryPath(Path attemptRecoverPath, String dagID); @Private static Path getSummaryRecoveryPath(Path attemptRecoverPath); static void mkDirForAM(FileSystem fs, Path dir); static FSDataOutputStream createFileForAM(FileSystem fs, Path filePath); @Private static ByteString compressByteArrayToByteString(byte[] inBytes); @Private static byte[] decompressByteStringToByteArray(ByteString byteString); static final FsPermission TEZ_AM_DIR_PERMISSION; static final FsPermission TEZ_AM_FILE_PERMISSION; static final String TEZ_SYSTEM_SUB_DIR; }### Answer: @Test public void testCreateTezSysStagingPath() throws Exception { String strAppId = "testAppId"; String expectedStageDir = RESOLVED_STAGE_DIR + File.separatorChar + TezCommonUtils.TEZ_SYSTEM_SUB_DIR + File.separatorChar + strAppId; String unResolvedStageDir = STAGE_DIR + File.separatorChar + TezCommonUtils.TEZ_SYSTEM_SUB_DIR + File.separatorChar + strAppId; Path stagePath = new Path(unResolvedStageDir); FileSystem fs = stagePath.getFileSystem(conf); if (fs.exists(stagePath)) { fs.delete(stagePath, true); } Assert.assertFalse(fs.exists(stagePath)); Path stageDir = TezCommonUtils.createTezSystemStagingPath(conf, strAppId); Assert.assertEquals(stageDir.toString(), expectedStageDir); Assert.assertTrue(fs.exists(stagePath)); }
### Question: TezCommonUtils { @Private public static Path getTezSystemStagingPath(Configuration conf, String strAppId) { Path baseStagingPath = getTezBaseStagingPath(conf); Path tezStagingDir; tezStagingDir = new Path(baseStagingPath, TEZ_SYSTEM_SUB_DIR); tezStagingDir = new Path(tezStagingDir, strAppId); return tezStagingDir; } static Path getTezBaseStagingPath(Configuration conf); @Private static Path createTezSystemStagingPath(Configuration conf, String strAppId); @Private static Path getTezSystemStagingPath(Configuration conf, String strAppId); @Private static Path getTezConfStagingPath(Path tezSysStagingPath); @Private static Path getTezSessionJarStagingPath(Path tezSysStagingPath); @Private static Path getTezBinPlanStagingPath(Path tezSysStagingPath); @Private static Path getTezTextPlanStagingPath(Path tezSysStagingPath); @Private static Path getRecoveryPath(Path tezSysStagingPath, Configuration conf); @Private static Path getAttemptRecoveryPath(Path recoveryPath, int attemptID); @Private static Path getDAGRecoveryPath(Path attemptRecoverPath, String dagID); @Private static Path getSummaryRecoveryPath(Path attemptRecoverPath); static void mkDirForAM(FileSystem fs, Path dir); static FSDataOutputStream createFileForAM(FileSystem fs, Path filePath); @Private static ByteString compressByteArrayToByteString(byte[] inBytes); @Private static byte[] decompressByteStringToByteArray(ByteString byteString); static final FsPermission TEZ_AM_DIR_PERMISSION; static final FsPermission TEZ_AM_FILE_PERMISSION; static final String TEZ_SYSTEM_SUB_DIR; }### Answer: @Test public void testTezSysStagingPath() throws Exception { String strAppId = "testAppId"; Path stageDir = TezCommonUtils.getTezSystemStagingPath(conf, strAppId); String expectedStageDir = RESOLVED_STAGE_DIR + File.separatorChar + TezCommonUtils.TEZ_SYSTEM_SUB_DIR + File.separatorChar + strAppId; Assert.assertEquals(stageDir.toString(), expectedStageDir); }
### Question: TezClientUtils { public static String maybeAddDefaultMemoryJavaOpts(String javaOpts, Resource resource, double maxHeapFactor) { if ((javaOpts != null && !javaOpts.isEmpty() && (javaOpts.contains("-Xmx") || javaOpts.contains("-Xms"))) || (resource.getMemory() <= 0)) { return javaOpts; } if (maxHeapFactor <= 0 || maxHeapFactor >= 1) { return javaOpts; } int maxMemory = (int)(resource.getMemory() * maxHeapFactor); maxMemory = maxMemory <= 0 ? 1 : maxMemory; return " -Xmx" + maxMemory + "m " + ( javaOpts != null ? javaOpts : ""); } 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 testDefaultMemoryJavaOpts() { final double factor = 0.8; String origJavaOpts = "-Xmx"; String javaOpts = TezClientUtils.maybeAddDefaultMemoryJavaOpts(origJavaOpts, Resource.newInstance(1000, 1), factor); Assert.assertEquals(origJavaOpts, javaOpts); origJavaOpts = ""; javaOpts = TezClientUtils.maybeAddDefaultMemoryJavaOpts(origJavaOpts, Resource.newInstance(1000, 1), factor); Assert.assertTrue(javaOpts.contains("-Xmx800m")); origJavaOpts = ""; javaOpts = TezClientUtils.maybeAddDefaultMemoryJavaOpts(origJavaOpts, Resource.newInstance(1, 1), factor); Assert.assertTrue(javaOpts.contains("-Xmx1m")); origJavaOpts = ""; javaOpts = TezClientUtils.maybeAddDefaultMemoryJavaOpts(origJavaOpts, Resource.newInstance(-1, 1), factor); Assert.assertEquals(origJavaOpts, javaOpts); origJavaOpts = ""; javaOpts = TezClientUtils.maybeAddDefaultMemoryJavaOpts(origJavaOpts, Resource.newInstance(355, 1), factor); Assert.assertTrue(javaOpts.contains("-Xmx284m")); origJavaOpts = " -Xms100m "; javaOpts = TezClientUtils.maybeAddDefaultMemoryJavaOpts(origJavaOpts, Resource.newInstance(355, 1), factor); Assert.assertFalse(javaOpts.contains("-Xmx284m")); Assert.assertTrue(javaOpts.contains("-Xms100m")); origJavaOpts = ""; javaOpts = TezClientUtils.maybeAddDefaultMemoryJavaOpts(origJavaOpts, Resource.newInstance(355, 1), 0); Assert.assertEquals(origJavaOpts, javaOpts); origJavaOpts = ""; javaOpts = TezClientUtils.maybeAddDefaultMemoryJavaOpts(origJavaOpts, Resource.newInstance(355, 1), 100); Assert.assertEquals(origJavaOpts, javaOpts); }
### 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: InputReadyTracker implements InputReadyCallback { public Input waitForAnyInputReady(Collection<Input> inputs) throws InterruptedException { Preconditions.checkArgument(inputs != null && inputs.size() > 0, "At least one input should be specified"); InputReadyMonitor inputReadyMonitor = new InputReadyMonitor(inputs, true); return inputReadyMonitor.awaitCondition(); } InputReadyTracker(); void setInputIsReady(Input input); Input waitForAnyInputReady(Collection<Input> inputs); void waitForAllInputsReady(Collection<Input> inputs); @Override // TODO Remove with TEZ-866 void setInputReady(Input input); void setGroupedInputs(Collection<MergedLogicalInput> inputGroups); }### Answer: @Test(timeout = 5000) public void testWithoutGrouping2() throws InterruptedException { InputReadyTracker inputReadyTracker = new InputReadyTracker(); ControlledReadyInputForTest input1 = new ControlledReadyInputForTest(inputReadyTracker); ControlledReadyInputForTest input2 = new ControlledReadyInputForTest(inputReadyTracker); ControlledReadyInputForTest input3 = new ControlledReadyInputForTest(inputReadyTracker); List<Input> requestList; long startTime = 0l; long readyTime = 0l; requestList = new ArrayList<Input>(); requestList.add(input1); requestList.add(input2); requestList.add(input3); startTime = System.currentTimeMillis(); setDelayedInputReady(input2); Input readyInput = inputReadyTracker.waitForAnyInputReady(requestList); assertEquals(input2, readyInput); readyTime = System.currentTimeMillis(); assertTrue(input2.isReady); assertTrue(readyTime >= startTime + SLEEP_TIME); assertFalse(input1.isReady); assertFalse(input3.isReady); requestList = new ArrayList<Input>(); requestList.add(input1); requestList.add(input3); startTime = System.currentTimeMillis(); setDelayedInputReady(input1); readyInput = inputReadyTracker.waitForAnyInputReady(requestList); assertEquals(input1, readyInput); readyTime = System.currentTimeMillis(); assertTrue(input1.isReady); assertTrue(readyTime >= startTime + SLEEP_TIME); assertTrue(input2.isReady); assertFalse(input3.isReady); requestList = new ArrayList<Input>(); requestList.add(input3); startTime = System.currentTimeMillis(); setDelayedInputReady(input3); readyInput = inputReadyTracker.waitForAnyInputReady(requestList); assertEquals(input3, readyInput); readyTime = System.currentTimeMillis(); assertTrue(input3.isReady); assertTrue(readyTime >= startTime + SLEEP_TIME); assertTrue(input1.isReady); assertTrue(input2.isReady); }
### 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: VertexImpl implements org.apache.tez.dag.app.dag.Vertex, EventHandler<VertexEvent> { @Override public List<String> getDiagnostics() { readLock.lock(); try { return diagnostics; } finally { readLock.unlock(); } } VertexImpl(TezVertexID vertexId, VertexPlan vertexPlan, String vertexName, Configuration conf, EventHandler eventHandler, TaskAttemptListener taskAttemptListener, Clock clock, TaskHeartbeatHandler thh, boolean commitVertexOutputs, AppContext appContext, VertexLocationHint vertexLocationHint, Map<String, VertexGroupInfo> dagVertexGroups, JavaProfilerOptions profilerOpts); @Override TezVertexID getVertexId(); @Override VertexPlan getVertexPlan(); @Override int getDistanceFromRoot(); @Override String getName(); @Override Task getTask(TezTaskID taskID); @Override Task getTask(int taskIndex); @Override int getTotalTasks(); @Override int getCompletedTasks(); @Override int getSucceededTasks(); @Override int getRunningTasks(); @Override TezCounters getAllCounters(); VertexStats getVertexStats(); static TezCounters incrTaskCounters( TezCounters counters, Collection<Task> tasks); static VertexStats updateVertexStats( VertexStats stats, Collection<Task> tasks); @Override List<String> getDiagnostics(); @Override float getProgress(); @Override ProgressBuilder getVertexProgress(); @Override VertexStatusBuilder getVertexStatus( Set<StatusGetOpts> statusOptions); @Override TaskLocationHint getTaskLocationHint(TezTaskID taskId); @Override Map<TezTaskID, Task> getTasks(); @Override VertexState getState(); @Override VertexTerminationCause getTerminationCause(); @Override AppContext getAppContext(); @Override VertexState restoreFromEvent(HistoryEvent historyEvent); @Override String getLogIdentifier(); @Override void scheduleTasks(List<TaskWithLocationHint> tasksToSchedule); @Override boolean setParallelism(int parallelism, VertexLocationHint vertexLocationHint, Map<String, EdgeManagerDescriptor> sourceEdgeManagers, Map<String, RootInputSpecUpdate> rootInputSpecUpdates); void setVertexLocationHint(VertexLocationHint vertexLocationHint); @Override /** * The only entry point to change the Vertex. */ void handle(VertexEvent event); @Private void constructFinalFullcounters(); @Override void setInputVertices(Map<Vertex, Edge> inVertices); @Override void setOutputVertices(Map<Vertex, Edge> outVertices); @Override void setAdditionalInputs(List<RootInputLeafOutputProto> inputs); @Nullable @Override Map<String, OutputCommitter> getOutputCommitters(); @Nullable @Private @VisibleForTesting OutputCommitter getOutputCommitter(String outputName); @Override void setAdditionalOutputs(List<RootInputLeafOutputProto> outputs); @Nullable @Override Map<String, RootInputLeafOutputDescriptor<InputDescriptor>> getAdditionalInputs(); @Nullable @Override Map<String, RootInputLeafOutputDescriptor<OutputDescriptor>> getAdditionalOutputs(); @Override int compareTo(Vertex other); @Override boolean equals(Object obj); @Override int hashCode(); @Override Map<Vertex, Edge> getInputVertices(); @Override Map<Vertex, Edge> getOutputVertices(); @Override int getInputVerticesCount(); @Override int getOutputVerticesCount(); @Override ProcessorDescriptor getProcessorDescriptor(); @Override DAG getDAG(); Resource getTaskResource(); @Override synchronized List<InputSpec> getInputSpecList(int taskIndex); @Override synchronized List<OutputSpec> getOutputSpecList(int taskIndex); @Override synchronized List<GroupInputSpec> getGroupInputSpecList(int taskIndex); @Override synchronized void addSharedOutputs(Set<String> outputs); @Override synchronized Set<String> getSharedOutputs(); }### Answer: @Test(timeout = 5000) public void testVertexKillDiagnosticsInInit() { initAllVertices(VertexState.INITED); VertexImpl v2 = vertices.get("vertex4"); killVertex(v2); String diagnostics = StringUtils.join(",", v2.getDiagnostics()).toLowerCase(); LOG.info("diagnostics v2: " + diagnostics); Assert.assertTrue(diagnostics.contains( "vertex received kill in inited state")); }
### Question: VertexImpl implements org.apache.tez.dag.app.dag.Vertex, EventHandler<VertexEvent> { @Nullable @Private @VisibleForTesting public OutputCommitter getOutputCommitter(String outputName) { if (this.outputCommitters != null) { return outputCommitters.get(outputName); } return null; } VertexImpl(TezVertexID vertexId, VertexPlan vertexPlan, String vertexName, Configuration conf, EventHandler eventHandler, TaskAttemptListener taskAttemptListener, Clock clock, TaskHeartbeatHandler thh, boolean commitVertexOutputs, AppContext appContext, VertexLocationHint vertexLocationHint, Map<String, VertexGroupInfo> dagVertexGroups, JavaProfilerOptions profilerOpts); @Override TezVertexID getVertexId(); @Override VertexPlan getVertexPlan(); @Override int getDistanceFromRoot(); @Override String getName(); @Override Task getTask(TezTaskID taskID); @Override Task getTask(int taskIndex); @Override int getTotalTasks(); @Override int getCompletedTasks(); @Override int getSucceededTasks(); @Override int getRunningTasks(); @Override TezCounters getAllCounters(); VertexStats getVertexStats(); static TezCounters incrTaskCounters( TezCounters counters, Collection<Task> tasks); static VertexStats updateVertexStats( VertexStats stats, Collection<Task> tasks); @Override List<String> getDiagnostics(); @Override float getProgress(); @Override ProgressBuilder getVertexProgress(); @Override VertexStatusBuilder getVertexStatus( Set<StatusGetOpts> statusOptions); @Override TaskLocationHint getTaskLocationHint(TezTaskID taskId); @Override Map<TezTaskID, Task> getTasks(); @Override VertexState getState(); @Override VertexTerminationCause getTerminationCause(); @Override AppContext getAppContext(); @Override VertexState restoreFromEvent(HistoryEvent historyEvent); @Override String getLogIdentifier(); @Override void scheduleTasks(List<TaskWithLocationHint> tasksToSchedule); @Override boolean setParallelism(int parallelism, VertexLocationHint vertexLocationHint, Map<String, EdgeManagerDescriptor> sourceEdgeManagers, Map<String, RootInputSpecUpdate> rootInputSpecUpdates); void setVertexLocationHint(VertexLocationHint vertexLocationHint); @Override /** * The only entry point to change the Vertex. */ void handle(VertexEvent event); @Private void constructFinalFullcounters(); @Override void setInputVertices(Map<Vertex, Edge> inVertices); @Override void setOutputVertices(Map<Vertex, Edge> outVertices); @Override void setAdditionalInputs(List<RootInputLeafOutputProto> inputs); @Nullable @Override Map<String, OutputCommitter> getOutputCommitters(); @Nullable @Private @VisibleForTesting OutputCommitter getOutputCommitter(String outputName); @Override void setAdditionalOutputs(List<RootInputLeafOutputProto> outputs); @Nullable @Override Map<String, RootInputLeafOutputDescriptor<InputDescriptor>> getAdditionalInputs(); @Nullable @Override Map<String, RootInputLeafOutputDescriptor<OutputDescriptor>> getAdditionalOutputs(); @Override int compareTo(Vertex other); @Override boolean equals(Object obj); @Override int hashCode(); @Override Map<Vertex, Edge> getInputVertices(); @Override Map<Vertex, Edge> getOutputVertices(); @Override int getInputVerticesCount(); @Override int getOutputVerticesCount(); @Override ProcessorDescriptor getProcessorDescriptor(); @Override DAG getDAG(); Resource getTaskResource(); @Override synchronized List<InputSpec> getInputSpecList(int taskIndex); @Override synchronized List<OutputSpec> getOutputSpecList(int taskIndex); @Override synchronized List<GroupInputSpec> getGroupInputSpecList(int taskIndex); @Override synchronized void addSharedOutputs(Set<String> outputs); @Override synchronized Set<String> getSharedOutputs(); }### Answer: @Test(timeout = 5000) public void testVertexCommitterInit() { initAllVertices(VertexState.INITED); VertexImpl v2 = vertices.get("vertex2"); Assert.assertNull(v2.getOutputCommitter("output")); VertexImpl v6 = vertices.get("vertex6"); Assert.assertTrue(v6.getOutputCommitter("outputx") instanceof CountingOutputCommitter); }
### Question: TaskImpl implements Task, EventHandler<TaskEvent> { @Override public List<TezEvent> getTaskAttemptTezEvents(TezTaskAttemptID attemptID, int fromEventId, int maxEvents) { List<TezEvent> events = EMPTY_TASK_ATTEMPT_TEZ_EVENTS; readLock.lock(); if (!attempts.containsKey(attemptID)) { throw new TezUncheckedException("Unknown TA: " + attemptID + " asking for events from task:" + getTaskId()); } try { if (tezEventsForTaskAttempts.size() > fromEventId) { int actualMax = Math.min(maxEvents, (tezEventsForTaskAttempts.size() - fromEventId)); int toEventId = actualMax + fromEventId; events = Collections.unmodifiableList(new ArrayList<TezEvent>( tezEventsForTaskAttempts.subList(fromEventId, toEventId))); LOG.info("TaskAttempt:" + attemptID + " sent events: (" + fromEventId + "-" + toEventId + ")"); } return events; } finally { readLock.unlock(); } } TaskImpl(TezVertexID vertexId, int taskIndex, EventHandler eventHandler, Configuration conf, TaskAttemptListener taskAttemptListener, Clock clock, TaskHeartbeatHandler thh, AppContext appContext, boolean leafVertex, Resource resource, ContainerContext containerContext); @Override TaskState getState(); @Override Map<TezTaskAttemptID, TaskAttempt> getAttempts(); @Override TaskAttempt getAttempt(TezTaskAttemptID attemptID); @Override Vertex getVertex(); @Override TezTaskID getTaskId(); @Override boolean isFinished(); @Override TaskReport getReport(); @Override TezCounters getCounters(); @Override float getProgress(); @Override List<TezEvent> getTaskAttemptTezEvents(TezTaskAttemptID attemptID, int fromEventId, int maxEvents); @Override List<String> getDiagnostics(); @Override TaskState restoreFromEvent(HistoryEvent historyEvent); @VisibleForTesting TaskStateInternal getInternalState(); @Override boolean canCommit(TezTaskAttemptID taskAttemptID); @Override boolean needsWaitAfterOutputConsumable(); @Override TezTaskAttemptID getOutputConsumableAttempt(); @Override TaskAttempt getSuccessfulAttempt(); @Override void handle(TaskEvent event); }### Answer: @Test public void testFetchedEventsModifyUnderlyingList() { List<TezEvent> fetchedList; TezTaskID taskId = getNewTaskID(); scheduleTaskAttempt(taskId); sendTezEventsToTask(taskId, 2); TezTaskAttemptID attemptID = mockTask.getAttemptList().iterator().next() .getID(); fetchedList = mockTask.getTaskAttemptTezEvents(attemptID, 0, 100); assertEquals(2, fetchedList.size()); sendTezEventsToTask(taskId, 4); assertEquals(2, fetchedList.size()); fetchedList = mockTask.getTaskAttemptTezEvents(attemptID, 0, 100); assertEquals(6, fetchedList.size()); }
### Question: TaskImpl implements Task, EventHandler<TaskEvent> { @Override public float getProgress() { readLock.lock(); try { TaskAttempt bestAttempt = selectBestAttempt(); if (bestAttempt == null) { return 0f; } return bestAttempt.getProgress(); } finally { readLock.unlock(); } } TaskImpl(TezVertexID vertexId, int taskIndex, EventHandler eventHandler, Configuration conf, TaskAttemptListener taskAttemptListener, Clock clock, TaskHeartbeatHandler thh, AppContext appContext, boolean leafVertex, Resource resource, ContainerContext containerContext); @Override TaskState getState(); @Override Map<TezTaskAttemptID, TaskAttempt> getAttempts(); @Override TaskAttempt getAttempt(TezTaskAttemptID attemptID); @Override Vertex getVertex(); @Override TezTaskID getTaskId(); @Override boolean isFinished(); @Override TaskReport getReport(); @Override TezCounters getCounters(); @Override float getProgress(); @Override List<TezEvent> getTaskAttemptTezEvents(TezTaskAttemptID attemptID, int fromEventId, int maxEvents); @Override List<String> getDiagnostics(); @Override TaskState restoreFromEvent(HistoryEvent historyEvent); @VisibleForTesting TaskStateInternal getInternalState(); @Override boolean canCommit(TezTaskAttemptID taskAttemptID); @Override boolean needsWaitAfterOutputConsumable(); @Override TezTaskAttemptID getOutputConsumableAttempt(); @Override TaskAttempt getSuccessfulAttempt(); @Override void handle(TaskEvent event); }### Answer: @Test public void testTaskProgress() { LOG.info("--- START: testTaskProgress ---"); TezTaskID taskId = getNewTaskID(); scheduleTaskAttempt(taskId); float progress = 0f; assert (mockTask.getProgress() == progress); launchTaskAttempt(mockTask.getLastAttempt().getID()); progress = 50f; updateAttemptProgress(mockTask.getLastAttempt(), progress); assert (mockTask.getProgress() == progress); progress = 100f; updateAttemptProgress(mockTask.getLastAttempt(), progress); assert (mockTask.getProgress() == progress); progress = 0f; updateAttemptState(mockTask.getLastAttempt(), TaskAttemptState.KILLED); assert (mockTask.getProgress() == progress); killRunningTaskAttempt(mockTask.getLastAttempt().getID()); assert (mockTask.getAttemptList().size() == 2); assert (mockTask.getProgress() == 0f); launchTaskAttempt(mockTask.getLastAttempt().getID()); progress = 50f; updateAttemptProgress(mockTask.getLastAttempt(), progress); assert (mockTask.getProgress() == progress); }
### Question: TaskImpl implements Task, EventHandler<TaskEvent> { @Override public void handle(TaskEvent event) { if (LOG.isDebugEnabled()) { LOG.debug("Processing TaskEvent " + event.getTaskID() + " of type " + event.getType() + " while in state " + getInternalState() + ". Event: " + event); } try { writeLock.lock(); TaskStateInternal oldState = getInternalState(); try { stateMachine.doTransition(event.getType(), event); } catch (InvalidStateTransitonException e) { LOG.error("Can't handle this event at current state for " + this.taskId, e); internalError(event.getType()); } if (oldState != getInternalState()) { LOG.info(taskId + " Task Transitioned from " + oldState + " to " + getInternalState()); } } finally { writeLock.unlock(); } } TaskImpl(TezVertexID vertexId, int taskIndex, EventHandler eventHandler, Configuration conf, TaskAttemptListener taskAttemptListener, Clock clock, TaskHeartbeatHandler thh, AppContext appContext, boolean leafVertex, Resource resource, ContainerContext containerContext); @Override TaskState getState(); @Override Map<TezTaskAttemptID, TaskAttempt> getAttempts(); @Override TaskAttempt getAttempt(TezTaskAttemptID attemptID); @Override Vertex getVertex(); @Override TezTaskID getTaskId(); @Override boolean isFinished(); @Override TaskReport getReport(); @Override TezCounters getCounters(); @Override float getProgress(); @Override List<TezEvent> getTaskAttemptTezEvents(TezTaskAttemptID attemptID, int fromEventId, int maxEvents); @Override List<String> getDiagnostics(); @Override TaskState restoreFromEvent(HistoryEvent historyEvent); @VisibleForTesting TaskStateInternal getInternalState(); @Override boolean canCommit(TezTaskAttemptID taskAttemptID); @Override boolean needsWaitAfterOutputConsumable(); @Override TezTaskAttemptID getOutputConsumableAttempt(); @Override TaskAttempt getSuccessfulAttempt(); @Override void handle(TaskEvent event); }### Answer: @SuppressWarnings("rawtypes") @Test public void testTaskSucceedAndRetroActiveFailure() { TezTaskID taskId = getNewTaskID(); scheduleTaskAttempt(taskId); launchTaskAttempt(mockTask.getLastAttempt().getID()); updateAttemptState(mockTask.getLastAttempt(), TaskAttemptState.RUNNING); mockTask.handle(new TaskEventTAUpdate(mockTask.getLastAttempt().getID(), TaskEventType.T_ATTEMPT_SUCCEEDED)); assertTaskSucceededState(); eventHandler.events.clear(); mockTask.handle(new TaskEventTAUpdate(mockTask.getLastAttempt() .getID(), TaskEventType.T_ATTEMPT_FAILED)); assertTaskScheduledState(); Event event = eventHandler.events.get(0); Assert.assertEquals(AMNodeEventType.N_TA_ENDED, event.getType()); event = eventHandler.events.get(eventHandler.events.size()-1); Assert.assertEquals(VertexEventType.V_TASK_RESCHEDULED, event.getType()); }
### Question: DAGImpl implements org.apache.tez.dag.app.dag.DAG, EventHandler<DAGEvent> { @Override public int getTotalVertices() { readLock.lock(); try { return numVertices; } finally { readLock.unlock(); } } DAGImpl(TezDAGID dagId, Configuration conf, DAGPlan jobPlan, EventHandler eventHandler, TaskAttemptListener taskAttemptListener, Credentials dagCredentials, Clock clock, String appUserName, TaskHeartbeatHandler thh, AppContext appContext); @Override TezDAGID getID(); @Override Configuration getConf(); @Override DAGPlan getJobPlan(); @Override boolean checkAccess(UserGroupInformation callerUGI, ApplicationAccessType jobOperation); @Override Vertex getVertex(TezVertexID vertexID); @Override boolean isUber(); @Override Credentials getCredentials(); @Override UserGroupInformation getDagUGI(); @Override DAGState restoreFromEvent(HistoryEvent historyEvent); @Override TezCounters getAllCounters(); static TezCounters incrTaskCounters( TezCounters counters, Collection<Vertex> vertices); @Override List<String> getDiagnostics(); @Override DAGReport getReport(); @Override float getProgress(); @Override Map<TezVertexID, Vertex> getVertices(); @Override DAGState getState(); @Override DAGStatusBuilder getDAGStatus(Set<StatusGetOpts> statusOptions); @Override VertexStatusBuilder getVertexStatus(String vertexName, Set<StatusGetOpts> statusOptions); @Override /** * The only entry point to change the DAG. */ void handle(DAGEvent event); @Private DAGState getInternalState(); @Override String getUserName(); @Override String getName(); @Override int getTotalVertices(); @Override int getSuccessfulVertices(); @Override Map<ApplicationAccessType, String> getJobACLs(); DAGState initializeDAG(); @Override Vertex getVertex(String vertexName); @Private void constructFinalFullcounters(); @Override boolean isComplete(); final Configuration conf; }### Answer: @Test(timeout = 5000) public void testDAGInit() { initDAG(dag); Assert.assertEquals(6, dag.getTotalVertices()); }
### 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: JavaProfilerOptions { public String getProfilerOptions(String jvmOpts, String vertexName, int taskIdx) { jvmOpts = (jvmOpts == null) ? "" : jvmOpts; vertexName = vertexName.replaceAll(" ", ""); String result = jvmProfilingOpts.replaceAll("__VERTEX_NAME__", vertexName) .replaceAll("__TASK_INDEX__", Integer.toString(taskIdx)); result = (jvmOpts + " " + result); LOG.info("Profiling option added to vertexName=" + vertexName + ", taskIdx=" + taskIdx + ", jvmOpts=" + result.trim()); return result.trim(); } JavaProfilerOptions(Configuration conf); String getProfilerOptions(String jvmOpts, String vertexName, int taskIdx); boolean shouldProfileJVM(String vertexName, int taskId); }### Answer: @Test public void testProfilingJVMOpts() { Configuration conf = new Configuration(); JavaProfilerOptions profilerOptions = getOptions(conf, "", ""); String jvmOpts = profilerOptions.getProfilerOptions("", "", 0); assertTrue(jvmOpts.trim().equals("")); profilerOptions = getOptions(conf, "", "dir=__VERTEX_NAME__"); jvmOpts = profilerOptions.getProfilerOptions("", "Map 1", 0); assertTrue(jvmOpts.equals("dir=Map1")); profilerOptions = getOptions(conf, "", "dir=__TASK_INDEX__"); jvmOpts = profilerOptions.getProfilerOptions("", "Map 1", 0); assertTrue(jvmOpts.equals("dir=0")); profilerOptions = getOptions(conf, "v[1,3,4]", "dir=/tmp/__VERTEX_NAME__/__TASK_INDEX__"); jvmOpts = profilerOptions.getProfilerOptions("", "v", 1); assertTrue(jvmOpts.equals("dir=/tmp/v/1")); jvmOpts = profilerOptions.getProfilerOptions("", "v", 3); assertTrue(jvmOpts.equals("dir=/tmp/v/3")); jvmOpts = profilerOptions.getProfilerOptions("", "v", 4); assertTrue(jvmOpts.equals("dir=/tmp/v/4")); }
### 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: MRHelpers { public static Configuration getBaseMRConfiguration(Configuration conf) { return getBaseJobConf(conf); } @LimitedPrivate("Hive, Pig") @Unstable static void translateVertexConfToTez(Configuration conf); @SuppressWarnings({ "rawtypes", "unchecked" }) @Private static org.apache.hadoop.mapreduce.InputSplit[] generateNewSplits( JobContext jobContext, String inputFormatName, int numTasks); @SuppressWarnings({ "rawtypes", "unchecked" }) @Private static org.apache.hadoop.mapred.InputSplit[] generateOldSplits( JobConf jobConf, String inputFormatName, int numTasks); static InputSplitInfoDisk generateInputSplits(Configuration conf, Path inputSplitsDir); static InputSplitInfoMem generateInputSplitsToMem(Configuration conf); @Private static MRSplitProto createSplitProto( T newSplit, SerializationFactory serializationFactory); @Private static MRSplitProto createSplitProto( org.apache.hadoop.mapred.InputSplit oldSplit); static void addLog4jSystemProperties(String logLevel, List<String> vargs); @SuppressWarnings("deprecation") static String getMapJavaOpts(Configuration conf); @SuppressWarnings("deprecation") static String getReduceJavaOpts(Configuration conf); static void doJobClientMagic(Configuration conf); @LimitedPrivate("Hive, Pig") @Unstable static byte[] createUserPayloadFromConf(Configuration conf); @LimitedPrivate("Hive, Pig") static ByteString createByteStringFromConf(Configuration conf); @LimitedPrivate("Hive, Pig") @Unstable static Configuration createConfFromUserPayload(byte[] bb); @LimitedPrivate("Hive, Pig") static Configuration createConfFromByteString(ByteString bs); static byte[] createMRInputPayload(byte[] configurationBytes, MRSplitsProto mrSplitsProto); static byte[] createMRInputPayload(Configuration conf, MRSplitsProto mrSplitsProto); static byte[] createMRInputPayloadWithGrouping(byte[] configurationBytes, String inputFormatName); static byte[] createMRInputPayloadWithGrouping(Configuration conf, String inputFormatName); static MRInputUserPayloadProto parseMRInputPayload(byte[] bytes); static void updateLocalResourcesForInputSplits( FileSystem fs, InputSplitInfo inputSplitInfo, Map<String, LocalResource> localResources); static Resource getMapResource(Configuration conf); static Resource getReduceResource(Configuration conf); static void updateEnvironmentForMRTasks(Configuration conf, Map<String, String> environment, boolean isMap); static Configuration getBaseMRConfiguration(Configuration conf); static Configuration getBaseMRConfiguration(); static void updateEnvironmentForMRAM(Configuration conf, Map<String, String> environment); static String getMRAMJavaOpts(Configuration conf); static void addMRInput(Vertex vertex, byte[] userPayload, Class<? extends TezRootInputInitializer> initClazz); static void addMROutput(Vertex vertex, byte[] userPayload); @Private static void addMROutputLegacy(Vertex vertex, byte[] userPayload); @SuppressWarnings("unchecked") static InputSplit createOldFormatSplitFromUserPayload( MRSplitProto splitProto, SerializationFactory serializationFactory); @SuppressWarnings("unchecked") static org.apache.hadoop.mapreduce.InputSplit createNewFormatSplitFromUserPayload( MRSplitProto splitProto, SerializationFactory serializationFactory); static void mergeMRBinaryTokens(Credentials creds, Configuration conf); }### Answer: @Test public void testGetBaseMRConf() { Configuration conf = MRHelpers.getBaseMRConfiguration(); Assert.assertNotNull(conf); conf = MRHelpers.getBaseMRConfiguration(new YarnConfiguration()); Assert.assertNotNull(conf); }
### Question: MRHelpers { public static String getMRAMJavaOpts(Configuration conf) { String mrAppMasterAdminOptions = conf.get( MRJobConfig.MR_AM_ADMIN_COMMAND_OPTS, MRJobConfig.DEFAULT_MR_AM_ADMIN_COMMAND_OPTS); String mrAppMasterUserOptions = conf.get(MRJobConfig.MR_AM_COMMAND_OPTS, MRJobConfig.DEFAULT_MR_AM_COMMAND_OPTS); return mrAppMasterAdminOptions.trim() + " " + mrAppMasterUserOptions.trim(); } @LimitedPrivate("Hive, Pig") @Unstable static void translateVertexConfToTez(Configuration conf); @SuppressWarnings({ "rawtypes", "unchecked" }) @Private static org.apache.hadoop.mapreduce.InputSplit[] generateNewSplits( JobContext jobContext, String inputFormatName, int numTasks); @SuppressWarnings({ "rawtypes", "unchecked" }) @Private static org.apache.hadoop.mapred.InputSplit[] generateOldSplits( JobConf jobConf, String inputFormatName, int numTasks); static InputSplitInfoDisk generateInputSplits(Configuration conf, Path inputSplitsDir); static InputSplitInfoMem generateInputSplitsToMem(Configuration conf); @Private static MRSplitProto createSplitProto( T newSplit, SerializationFactory serializationFactory); @Private static MRSplitProto createSplitProto( org.apache.hadoop.mapred.InputSplit oldSplit); static void addLog4jSystemProperties(String logLevel, List<String> vargs); @SuppressWarnings("deprecation") static String getMapJavaOpts(Configuration conf); @SuppressWarnings("deprecation") static String getReduceJavaOpts(Configuration conf); static void doJobClientMagic(Configuration conf); @LimitedPrivate("Hive, Pig") @Unstable static byte[] createUserPayloadFromConf(Configuration conf); @LimitedPrivate("Hive, Pig") static ByteString createByteStringFromConf(Configuration conf); @LimitedPrivate("Hive, Pig") @Unstable static Configuration createConfFromUserPayload(byte[] bb); @LimitedPrivate("Hive, Pig") static Configuration createConfFromByteString(ByteString bs); static byte[] createMRInputPayload(byte[] configurationBytes, MRSplitsProto mrSplitsProto); static byte[] createMRInputPayload(Configuration conf, MRSplitsProto mrSplitsProto); static byte[] createMRInputPayloadWithGrouping(byte[] configurationBytes, String inputFormatName); static byte[] createMRInputPayloadWithGrouping(Configuration conf, String inputFormatName); static MRInputUserPayloadProto parseMRInputPayload(byte[] bytes); static void updateLocalResourcesForInputSplits( FileSystem fs, InputSplitInfo inputSplitInfo, Map<String, LocalResource> localResources); static Resource getMapResource(Configuration conf); static Resource getReduceResource(Configuration conf); static void updateEnvironmentForMRTasks(Configuration conf, Map<String, String> environment, boolean isMap); static Configuration getBaseMRConfiguration(Configuration conf); static Configuration getBaseMRConfiguration(); static void updateEnvironmentForMRAM(Configuration conf, Map<String, String> environment); static String getMRAMJavaOpts(Configuration conf); static void addMRInput(Vertex vertex, byte[] userPayload, Class<? extends TezRootInputInitializer> initClazz); static void addMROutput(Vertex vertex, byte[] userPayload); @Private static void addMROutputLegacy(Vertex vertex, byte[] userPayload); @SuppressWarnings("unchecked") static InputSplit createOldFormatSplitFromUserPayload( MRSplitProto splitProto, SerializationFactory serializationFactory); @SuppressWarnings("unchecked") static org.apache.hadoop.mapreduce.InputSplit createNewFormatSplitFromUserPayload( MRSplitProto splitProto, SerializationFactory serializationFactory); static void mergeMRBinaryTokens(Credentials creds, Configuration conf); }### Answer: @Test public void testMRAMJavaOpts() { Configuration conf = new Configuration(); conf.set(MRJobConfig.MR_AM_ADMIN_COMMAND_OPTS, " -Dadminfoobar "); conf.set(MRJobConfig.MR_AM_COMMAND_OPTS, " -Duserfoo "); String opts = MRHelpers.getMRAMJavaOpts(conf); Assert.assertEquals("-Dadminfoobar -Duserfoo", opts); }
### 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: JpaDataStore implements DataStore { @Override public Set<Ack> removeAcknowledged(final String uaid, final Set<Ack> acked) { final JpaOperation<Set<Ack>> removeAck = new JpaOperation<Set<Ack>>() { @Override public Set<Ack> perform(final EntityManager em) { final List<String> channelIds = new ArrayList<String>(acked.size()); for (Ack ack : acked) { channelIds.add(ack.getChannelId()); } final Query delete = em.createQuery("DELETE from AckDTO c where c.channelId in (:channelIds)"); delete.setParameter("channelIds", channelIds); delete.executeUpdate(); final UserAgentDTO userAgent = em.find(UserAgentDTO.class, uaid); final Set<AckDTO> acks = userAgent.getAcks(); final Set<Ack> unacked = new HashSet<Ack>(acks.size()); for (AckDTO ackDto : acks) { unacked.add(new AckImpl(ackDto.getChannelId(), ackDto.getVersion())); } return unacked; } }; return jpaExecutor.execute(removeAck); } 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 removeAcknowledged() throws ChannelNotFoundException { final String uaid = UUIDUtil.newUAID(); final Channel channel1 = newChannel(uaid, UUID.randomUUID().toString(), 10); final Channel channel2 = newChannel(uaid, UUID.randomUUID().toString(), 2); jpaDataStore.saveChannel(channel1); jpaDataStore.saveChannel(channel2); jpaDataStore.saveUnacknowledged(channel1.getChannelId(), 11); jpaDataStore.saveUnacknowledged(channel2.getChannelId(), 3); final Set<Ack> storedUpdates = jpaDataStore.getUnacknowledged(uaid); assertThat(storedUpdates.size(), is(2)); jpaDataStore.removeAcknowledged(uaid, acks(new AckImpl(channel1.getChannelId(), 11))); assertThat(jpaDataStore.getUnacknowledged(uaid).size(), is(1)); }
### Question: JpaDataStore implements DataStore { @Override public Set<Ack> getUnacknowledged(final String uaid) { final JpaOperation<Set<Ack>> getUnacks = new JpaOperation<Set<Ack>>() { @Override public Set<Ack> perform(final EntityManager em) { final UserAgentDTO userAgent = em.find(UserAgentDTO.class, uaid); if (userAgent == null) { return Collections.emptySet(); } final HashSet<Ack> acks = new HashSet<Ack>(); for (AckDTO ackDTO : userAgent.getAcks()) { acks.add(new AckImpl(ackDTO.getChannelId(), ackDTO.getVersion())); } return acks; } }; return jpaExecutor.execute(getUnacks); } 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 getUnacknowledgedNoChannelsSavedYet() { final String uaid = UUIDUtil.newUAID(); final Set<Ack> storedUpdates = jpaDataStore.getUnacknowledged(uaid); assertThat(storedUpdates.size(), is(0)); } @Test public void getUnacknowledged() throws ChannelNotFoundException { final String uaid = UUIDUtil.newUAID(); final Channel channel1 = newChannel(uaid, UUID.randomUUID().toString(), 1); final Channel channel2 = newChannel(uaid, UUID.randomUUID().toString(), 2); jpaDataStore.saveChannel(channel1); jpaDataStore.saveChannel(channel2); jpaDataStore.saveUnacknowledged(channel1.getChannelId(), 10); jpaDataStore.saveUnacknowledged(channel2.getChannelId(), 10); assertThat(jpaDataStore.getUnacknowledged(uaid).size(), is(2)); }