public RestResponse<ServerInfo> makeRootRequest() { return getServerInfo(); }
private int canMakeCliRequest(final String username, final String password) { try (KsqlRestClient restClient = new KsqlRestClient(REST_APP.getHttpListener().toString())) { if (!username.isEmpty()) { restClient.setupAuthenticationCredentials(username, password); } final RestResponse<ServerInfo> response = restClient.getServerInfo(); if (response.isSuccessful()) { return Code.OK.getCode(); } return response.getErrorMessage().getErrorCode(); } }
@Override public void makeKsqlRequest(final String statements) { try { printKsqlResponse(restClient.makeKsqlRequest(statements)); } catch (IOException e) { throw new KsqlException(e); } }
@Override public void execute(final List<String> args, final PrintWriter terminal) { CliCmdUtil.ensureArgCountBounds(args, 0, 1, HELP); if (args.isEmpty()) { terminal.println(restClient.getServerAddress()); return; } else { final String serverAddress = args.get(0); restClient.setServerAddress(serverAddress); terminal.println("Server now: " + serverAddress); } validateClient(terminal, restClient); }
) { try { final RestResponse restResponse = restClient.makeRootRequest(); if (restResponse.isErroneous()) { final KsqlErrorMessage ksqlError = restResponse.getErrorMessage(); writer.println("**************** ERROR ********************"); writer.println("Remote server address may not be valid."); writer.println("Address: " + restClient.getServerAddress()); writer.println(ErrorMessageUtil.buildErrorMessage(exception)); writer.println("*******************************************");
private void displayWelcomeMessage() { String serverVersion; try { serverVersion = restClient.getServerInfo().getResponse().getVersion(); } catch (final Exception exception) { serverVersion = "<unknown>"; } final String cliVersion = Version.getVersion(); final String helpReminderMessage = "Having trouble? " + "Type 'help' (case-insensitive) for a rundown of how things work!"; final PrintWriter writer = terminal.writer(); // Want to center the logo, but in the case of something like a fullscreen terminal, just // centering around the help message (longest single line of text in the welcome message) // should be enough; looks a little weird if you try to center the logo on a wide enough // screen and it just kind of ends up out in the middle of nowhere; hence, the call to // Math.min(terminal.getWidth(), helpReminderMessage.length()) final int consoleWidth = Math.min(terminal.getWidth(), helpReminderMessage.length()); WelcomeMsgUtils.displayWelcomeMessage(consoleWidth, writer); writer.printf( "CLI v%s, Server v%s located at %s%n", cliVersion, serverVersion, restClient.getServerAddress() ); writer.println(); writer.println(helpReminderMessage); writer.println(); terminal.flush(); }
@Test public void shouldPrintErrorIfCantConnectToRestServer() throws Exception { givenRunInteractivelyWillExit(); final KsqlRestClient mockRestClient = EasyMock.mock(KsqlRestClient.class); EasyMock.expect(mockRestClient.makeRootRequest()).andThrow(new KsqlRestClientException("Boom", new ProcessingException(""))); EasyMock.expect(mockRestClient.getServerInfo()).andReturn( RestResponse.of(new ServerInfo("1.x", "testClusterId", "testServiceId"))); EasyMock.expect(mockRestClient.getServerAddress()).andReturn(new URI("http://someserver:8008")).anyTimes(); EasyMock.replay(mockRestClient); new Cli(1L, 1L, mockRestClient, console) .runInteractively(); assertThat(terminal.getOutputString(), containsString("Remote server address may not be valid")); }
private static void createStreams() { try (final KsqlRestClient ksqlRestClient = new KsqlRestClient(REST_APP.getHttpListener().toString()) ) { final RestResponse createStreamResponse = ksqlRestClient .makeKsqlRequest(String.format( "CREATE STREAM %s (viewtime bigint, pageid varchar, userid varchar)" + " WITH (kafka_topic='pageviews', value_format='json');", PAGE_VIEW_STREAM)); assertTrue(createStreamResponse.isSuccessful()); } } }
@Test public void shouldPrintServerAddressWhenEmptyStringArg() throws Exception { expect(restClient.makeRootRequest()).andReturn(RestResponse.successful(SERVER_INFO)); expect(restClient.getServerAddress()).andReturn(new URI(INITIAL_SERVER_ADDRESS)); restClient.setServerAddress(anyString()); expectLastCall().andThrow(new AssertionError("should not set address")); replay(restClient); command.execute(ImmutableList.of(), terminal); assertThat(out.toString(), equalTo(INITIAL_SERVER_ADDRESS + "\n")); }
@Test(expected = KsqlRestClientException.class) public void shouldThrowOnInvalidServerAddress() { new KsqlRestClient("not-valid-address"); }
private static void runStatement(final String statement, final KsqlRestClient restClient) { final RestResponse response = restClient.makeKsqlRequest(statement); Assert.assertThat(response.isSuccessful(), is(true)); final KsqlEntityList entityList = ((KsqlEntityList) response.get()); Assert.assertThat(entityList.size(), equalTo(1)); Assert.assertThat(entityList.get(0), instanceOf(CommandStatusEntity.class)); final CommandStatusEntity entity = (CommandStatusEntity) entityList.get(0); final CommandStatus status = entity.getCommandStatus(); Assert.assertThat(status, not(CommandStatus.Status.ERROR)); if (status.getStatus() != Status.SUCCESS) { assertThatEventually( "", () -> { final RestResponse statusResponse = restClient .makeStatusRequest(entity.getCommandId().toString()); Assert.assertThat(statusResponse.isSuccessful(), is(true)); Assert.assertThat(statusResponse.get(), instanceOf(CommandStatus.class)); return ((CommandStatus) statusResponse.get()).getStatus(); }, anyOf( is(CommandStatus.Status.SUCCESS), is(CommandStatus.Status.TERMINATED), is(CommandStatus.Status.ERROR)), 120, TimeUnit.SECONDS ); } }
@Test public void shouldRestClientServerAddressWhenNonEmptyStringArg() { expect(restClient.makeRootRequest()).andReturn(RestResponse.successful(SERVER_INFO)); restClient.setServerAddress(VALID_SERVER_ADDRESS); expectLastCall(); replay(restClient); command.execute(ImmutableList.of(VALID_SERVER_ADDRESS), terminal); verify(restClient); }
public static void main(final String[] args) throws IOException { final Options options = args.length == 0 ? Options.parse("http://localhost:8088") : Options.parse(args); if (options == null) { System.exit(-1); } try { final Properties properties = loadProperties(options.getConfigFile()); try (KsqlRestClient restClient = new KsqlRestClient(options.getServer(), properties)) { options.getUserNameAndPassword().ifPresent( creds -> restClient.setupAuthenticationCredentials(creds.left, creds.right) ); final KsqlVersionCheckerAgent versionChecker = new KsqlVersionCheckerAgent(() -> false); versionChecker.start(KsqlModuleType.CLI, properties); try (Cli cli = Cli.build( options.getStreamedQueryRowLimit(), options.getStreamedQueryTimeoutMs(), options.getOutputFormat(), restClient) ) { cli.runInteractively(); } } } catch (final Exception e) { final String msg = ErrorMessageUtil.buildErrorMessage(e); LOGGER.error(msg); System.err.println(msg); System.exit(-1); } }
@Test public void shouldOutputNewServerDetails() { expect(restClient.makeRootRequest()).andReturn(RestResponse.successful(SERVER_INFO)); replay(restClient); command.execute(ImmutableList.of(VALID_SERVER_ADDRESS), terminal); assertThat(out.toString(), containsString("Server now: " + VALID_SERVER_ADDRESS)); }
private void handleStreamedQuery(final String query) throws IOException { final RestResponse<KsqlRestClient.QueryStream> queryResponse = restClient.makeQueryRequest(query); LOGGER.debug("Handling streamed query"); if (!queryResponse.isSuccessful()) { terminal.printErrorMessage(queryResponse.getErrorMessage()); } else { try (KsqlRestClient.QueryStream queryStream = queryResponse.getResponse(); StatusClosable ignored = terminal.setStatusMessage("Press CTRL-C to interrupt")) { streamResults(queryStream); } } }
@Test public void shouldReturnStatusForSpecificCommand() { // When: final RestResponse<CommandStatus> response = ksqlRestClient.makeStatusRequest("TOPIC/c1/CREATE"); // Then: assertThat(response, is(notNullValue())); assertThat(response.isSuccessful(), is(true)); assertThat(response.getResponse().getStatus(), is(CommandStatus.Status.SUCCESS)); }
@Test(expected = KsqlRestClientException.class) public void shouldThrowIfRestClientThrowsOnSet() { restClient.setServerAddress("localhost:8088"); expectLastCall().andThrow(new KsqlRestClientException("Boom")); replay(restClient); command.execute(ImmutableList.of("localhost:8088"), terminal); }
@Test public void shouldPrintErrorOnUnsupportedAPI() throws Exception { givenRunInteractivelyWillExit(); final KsqlRestClient mockRestClient = EasyMock.mock(KsqlRestClient.class); EasyMock.expect(mockRestClient.makeRootRequest()).andReturn( RestResponse.erroneous( new KsqlErrorMessage( Errors.toErrorCode(NOT_ACCEPTABLE.getStatusCode()), "Minimum supported client version: 1.0"))); EasyMock.expect(mockRestClient.getServerInfo()).andReturn( RestResponse.of(new ServerInfo("1.x", "testClusterId", "testServiceId"))); EasyMock.expect(mockRestClient.getServerAddress()).andReturn(new URI("http://someserver:8008")); EasyMock.replay(mockRestClient); new Cli(1L, 1L, mockRestClient, console) .runInteractively(); Assert.assertThat( terminal.getOutputString(), containsString("This CLI version no longer supported")); Assert.assertThat( terminal.getOutputString(), containsString("Minimum supported client version: 1.0")); }
@SuppressWarnings("unchecked") private <T> void givenServerWillReturn(final int statusCode, final Optional<T> entity) { final Response response = mock(Response.class); when(response.getStatus()).thenReturn(statusCode); entity.ifPresent(e -> when(response.readEntity((Class<T>) e.getClass())).thenReturn(e)); final Invocation.Builder builder = mock(Invocation.Builder.class); when(builder.get()).thenReturn(response); when(builder.post(any())).thenReturn(response); final WebTarget target = mock(WebTarget.class); when(target.path(any())).thenReturn(target); when(target.request(MediaType.APPLICATION_JSON_TYPE)).thenReturn(builder); final Client client = mock(Client.class); when(client.target(any(URI.class))).thenReturn(target); ksqlRestClient = new KsqlRestClient(client, "http://0.0.0.0", Collections.emptyMap()); }
@Test public void shouldPrintErrorOnErrorResponseFromRestClient() { expect(restClient.makeRootRequest()).andReturn(RestResponse.erroneous( Errors.ERROR_CODE_SERVER_ERROR, "it is broken")); replay(restClient); command.execute(ImmutableList.of(VALID_SERVER_ADDRESS), terminal); assertThat(out.toString(), containsString("it is broken")); }