diff --git a/.gitignore b/.gitignore index eaa87602b..648440ddb 100644 --- a/.gitignore +++ b/.gitignore @@ -24,6 +24,7 @@ main/.classpath unit/.classpath build/* out/* +**/out/* .idea/* .DS_Store Thumbs.db diff --git a/README.md b/README.md index 12e960a6a..999b9a1cf 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ A highly flexible and configurable tool for testing interactions of SOA applicat ##### Why the word "stubby"? It is a stub HTTP server after all, hence the "stubby". Also, in Australian slang "stubby" means _beer bottle_ -## User manual for stubby4j v5.1.0 +## User manual for stubby4j v5.1.1 ### Table of contents * [Quick start example](#quick-start-example) @@ -137,8 +137,8 @@ Run `gradle cobertura` command to: ### Third-party dependencies * __javax.servlet-api-3.1.0.jar__ -* jetty-server-9.4.6.v20170531.jar -* jetty-servlets-9.4.6.v20170531.jar +* jetty-server-9.4.8.v20171121.jar +* jetty-servlets-9.4.8.v20171121.jar * commons-cli-1.2.jar * snakeyaml-1.17.jar * jsonassert-1.3.0.jar @@ -158,12 +158,12 @@ The following are the stubby4j artifacts that are hosted on [Maven Central][mave ##### Gradle ```xml -compile("io.github.azagniotov:stubby4j:5.1.0") +compile("io.github.azagniotov:stubby4j:5.1.1") ``` or by adding a `classifier` to the JAR name like `no-dependencies` or `no-jetty`, i.e.: ```xml -compile("io.github.azagniotov:stubby4j:5.1.0:no-jetty") +compile("io.github.azagniotov:stubby4j:5.1.1:no-jetty") ``` ##### Maven @@ -171,7 +171,7 @@ compile("io.github.azagniotov:stubby4j:5.1.0:no-jetty") io.github.azagniotov stubby4j - 5.1.0 + 5.1.1 ``` or by adding a `classifier` to the JAR name like `no-dependencies` or `no-jetty`, i.e.: @@ -180,7 +180,7 @@ or by adding a `classifier` to the JAR name like `no-dependencies` or `no-jetty` io.github.azagniotov stubby4j - 5.1.0 + 5.1.1 no-dependencies ``` @@ -189,17 +189,17 @@ or by adding a `classifier` to the JAR name like `no-dependencies` or `no-jetty` Run `gradle install` command to: -* Install `stubby4j-5.1.1-SNAPSHOT*.jar` to local `~/.m2/repository` -* All the artifacts will be installed under `~/.m2/repository/{groupId}/{artifactId}/{version}/`, e.g.: `~/.m2/repository/io/github/azagniotov/stubby4j/5.1.1-SNAPSHOT/` +* Install `stubby4j-5.1.2-SNAPSHOT*.jar` to local `~/.m2/repository` +* All the artifacts will be installed under `~/.m2/repository/{groupId}/{artifactId}/{version}/`, e.g.: `~/.m2/repository/io/github/azagniotov/stubby4j/5.1.2-SNAPSHOT/` Now you can include locally installed stubby4j `SNAPSHOT` artifacts in your project: ```xml -compile("io.github.azagniotov:stubby4j:5.1.1-SNAPSHOT") +compile("io.github.azagniotov:stubby4j:5.1.2-SNAPSHOT") ``` or by adding a `classifier` to the JAR name like `no-dependencie`s or `no-jetty`, i.e.: ```xml -compile("io.github.azagniotov:stubby4j:5.1.1-SNAPSHOT:no-jetty") +compile("io.github.azagniotov:stubby4j:5.1.2-SNAPSHOT:no-jetty") ``` @@ -1179,7 +1179,11 @@ You can start-up and manage stubby4j with the help of [StubbyClient](main/java/i ### Change log -##### 5.1.1-SNAPSHOT +##### 5.1.2-SNAPSHOT + +##### 5.1.1 +* Added ANSITerminal back. it is operational alongside the SLF4J for the cases when stubby is running as a standalone jar +* Upgraded from Jetty `9.4.6.v20170531` to `9.4.8.v20171121` ##### 5.1.0 * Pull request #83 - ANSITerminal was replaced with SLF4J. It is up to the stuby4j consumer to choose their own logging implementation (https://github.com/asarkar) diff --git a/conf/gradle/dependency.gradle b/conf/gradle/dependency.gradle index a36e2ddfe..894b44715 100644 --- a/conf/gradle/dependency.gradle +++ b/conf/gradle/dependency.gradle @@ -1,7 +1,7 @@ // vim: ft=groovy dependencies { - compile "org.eclipse.jetty:jetty-server:9.4.6.v20170531" - compile "org.eclipse.jetty:jetty-servlets:9.4.6.v20170531" + compile "org.eclipse.jetty:jetty-server:9.4.8.v20171121" + compile "org.eclipse.jetty:jetty-servlets:9.4.8.v20171121" compile "commons-cli:commons-cli:1.2" compile "org.yaml:snakeyaml:1.17" compile "org.skyscreamer:jsonassert:1.3.0" diff --git a/functional/java/io/github/azagniotov/stubby4j/StubsPortalTest.java b/functional/java/io/github/azagniotov/stubby4j/StubsPortalTest.java index dac57c7b6..ad2e6212b 100644 --- a/functional/java/io/github/azagniotov/stubby4j/StubsPortalTest.java +++ b/functional/java/io/github/azagniotov/stubby4j/StubsPortalTest.java @@ -1004,6 +1004,8 @@ public void should_NotReturnExpectedRecordedResponse_FromValidUrl_WhenQueryValue @Test public void should_ReturnExpectedRecordedResponse_OnSubsequentCallToValidUrl() throws Exception { + ANSITerminal.muteConsole(false); + final ByteArrayOutputStream consoleCaptor = new ByteArrayOutputStream(); final boolean NO_AUTO_FLUSH = false; final PrintStream oldPrintStream = System.out; @@ -1023,6 +1025,8 @@ public void should_ReturnExpectedRecordedResponse_OnSubsequentCallToValidUrl() t String firstCallResponseContent = actualResponse.parseAsString().trim(); assertThat(firstCallResponseContent).contains("STANDARD"); + // Make sure we only hitting recordable source once + assertThat(actualConsoleOutput).contains("Recording HTTP response using"); if (idx == LIMIT) { System.setOut(oldPrintStream); @@ -1030,4 +1034,4 @@ public void should_ReturnExpectedRecordedResponse_OnSubsequentCallToValidUrl() t } } } -} \ No newline at end of file +} diff --git a/gradle.properties b/gradle.properties index edf278b36..68a0a382e 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,5 +3,5 @@ org.gradle.parallel=true configureondemand=true stubbyProjectName=stubby4j stubbyProjectGroup=io.github.azagniotov -version=5.1.1-SNAPSHOT +version=5.1.2-SNAPSHOT diff --git a/integration/java/io/github/azagniotov/stubby4j/utils/ConsoleUtilsTest.java b/integration/java/io/github/azagniotov/stubby4j/utils/ConsoleUtilsTest.java new file mode 100644 index 000000000..b7309287f --- /dev/null +++ b/integration/java/io/github/azagniotov/stubby4j/utils/ConsoleUtilsTest.java @@ -0,0 +1,149 @@ +package io.github.azagniotov.stubby4j.utils; + +import io.github.azagniotov.stubby4j.cli.ANSITerminal; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; + +import static com.google.common.truth.Truth.assertThat; +import static org.mockito.Mockito.when; + +/** + * @author: Alexander Zagniotov + * Created: 4/22/13 3:33 PM + */ +@RunWith(MockitoJUnitRunner.class) +public class ConsoleUtilsTest { + + private static final String URI = "/some/uri/to/resource/123"; + + @Mock + private HttpServletRequest mockHttpServletRequest; + + @Mock + private HttpServletResponse mockHttpServletResponse; + + private ByteArrayOutputStream consoleCaptor; + + @BeforeClass + public static void beforeClass() throws Exception { + ANSITerminal.muteConsole(false); + } + + @Before + public void beforeEach() throws Exception { + consoleCaptor = new ByteArrayOutputStream(); + final boolean NO_AUTO_FLUSH = false; + System.setOut(new PrintStream(consoleCaptor, NO_AUTO_FLUSH, StringUtils.UTF_8)); + + when(mockHttpServletRequest.getRequestURI()).thenReturn(URI); + } + + @After + public void afterEach() throws Exception { + System.setOut(System.out); + } + + @Test + public void shouldPrintToConsoleExpectedErrorWithColor_WhenStatus_500() throws Exception { + + final int expectedStatus = 500; + final String expectedConsoleOutput = String.format("%s [%s] Server Error\u001B[0m", expectedStatus, URI); + final String expectedConsoleColor = "[31m"; + + when(mockHttpServletResponse.getStatus()).thenReturn(expectedStatus); + + ConsoleUtils.logOutgoingResponse(mockHttpServletRequest.getRequestURI(), mockHttpServletResponse); + final String actualConsoleOutput = consoleCaptor.toString(StringUtils.UTF_8).trim(); + + assertThat(actualConsoleOutput).contains(expectedConsoleOutput); + assertThat(actualConsoleOutput).contains(expectedConsoleColor); + } + + @Test + public void shouldPrintToConsoleExpectedErrorWithColor_WhenStatus_301() throws Exception { + + final int expectedStatus = 301; + final String expectedConsoleOutput = String.format("%s [%s] Moved Permanently\u001B[0m", expectedStatus, URI); + final String expectedConsoleColor = "[33m"; + + when(mockHttpServletResponse.getStatus()).thenReturn(expectedStatus); + + ConsoleUtils.logOutgoingResponse(mockHttpServletRequest.getRequestURI(), mockHttpServletResponse); + final String actualConsoleOutput = consoleCaptor.toString(StringUtils.UTF_8).trim(); + + assertThat(actualConsoleOutput).contains(expectedConsoleOutput); + assertThat(actualConsoleOutput).contains(expectedConsoleColor); + } + + @Test + public void shouldPrintToConsoleExpectedErrorWithColor_WhenStatus_201() throws Exception { + + final int expectedStatus = 201; + final String expectedConsoleOutput = String.format("%s [%s] Created\u001B[0m", expectedStatus, URI); + final String expectedConsoleColor = "[32m"; + + when(mockHttpServletResponse.getStatus()).thenReturn(expectedStatus); + + ConsoleUtils.logOutgoingResponse(mockHttpServletRequest.getRequestURI(), mockHttpServletResponse); + final String actualConsoleOutput = consoleCaptor.toString(StringUtils.UTF_8).trim(); + + assertThat(actualConsoleOutput).contains(expectedConsoleOutput); + assertThat(actualConsoleOutput).contains(expectedConsoleColor); + } + + @Test + public void shouldPrintToConsoleExpectedErrorWithColor_WhenStatus_200() throws Exception { + + final int expectedStatus = 200; + final String expectedConsoleOutput = String.format("%s [%s] OK\u001B[0m", expectedStatus, URI); + final String expectedConsoleColor = "[32m"; + + when(mockHttpServletResponse.getStatus()).thenReturn(expectedStatus); + + ConsoleUtils.logOutgoingResponse(mockHttpServletRequest.getRequestURI(), mockHttpServletResponse); + final String actualConsoleOutput = consoleCaptor.toString(StringUtils.UTF_8).trim(); + + assertThat(actualConsoleOutput).contains(expectedConsoleOutput); + assertThat(actualConsoleOutput).contains(expectedConsoleColor); + } + + @Test + public void shouldPrintToConsoleExpectedErrorWithColor_WhenStatus_100() throws Exception { + + final int expectedStatus = 100; + final String expectedConsoleOutput = String.format("%s [%s] Continue\u001B[0m", expectedStatus, URI); + final String expectedConsoleColor = "[34m"; + + when(mockHttpServletResponse.getStatus()).thenReturn(expectedStatus); + + ConsoleUtils.logOutgoingResponse(mockHttpServletRequest.getRequestURI(), mockHttpServletResponse); + final String actualConsoleOutput = consoleCaptor.toString(StringUtils.UTF_8).trim(); + + assertThat(actualConsoleOutput).contains(expectedConsoleOutput); + assertThat(actualConsoleOutput).contains(expectedConsoleColor); + } + + @Test + public void shouldPrintToConsoleExpectedErrorWithColor_WhenStatus_LessThan100() throws Exception { + + final int expectedStatus = 99; + final String expectedConsoleOutput = String.format("%s [%s] 99\u001B[0m", expectedStatus, URI); + + when(mockHttpServletResponse.getStatus()).thenReturn(expectedStatus); + + ConsoleUtils.logOutgoingResponse(mockHttpServletRequest.getRequestURI(), mockHttpServletResponse); + final String actualConsoleOutput = consoleCaptor.toString(StringUtils.UTF_8).trim(); + + assertThat(actualConsoleOutput).contains(expectedConsoleOutput); + } +} diff --git a/integration/java/io/github/azagniotov/stubby4j/yaml/YAMLParserTest.java b/integration/java/io/github/azagniotov/stubby4j/yaml/YAMLParserTest.java index 208851d5d..9e5ff7b57 100644 --- a/integration/java/io/github/azagniotov/stubby4j/yaml/YAMLParserTest.java +++ b/integration/java/io/github/azagniotov/stubby4j/yaml/YAMLParserTest.java @@ -12,7 +12,9 @@ import org.junit.Test; import org.junit.rules.ExpectedException; +import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.io.PrintStream; import java.util.List; import static com.google.common.truth.Truth.assertThat; @@ -298,6 +300,36 @@ public void shouldUnmarshall_WhenYAMLValid_WithFileFailedToLoadAndPostSet() thro assertThat(actualRequest.getPostBody()).isEqualTo(expectedPost); } + @Test + public void shouldCaptureConsoleErrorOutput_WhenYAMLValid_WithFileFailedToLoadAndPostSet() throws Exception { + + final String stubbedRequestFile = "../../very.big.soap.request.xml"; + + final String expectedPost = "{\"message\", \"Hello, this is HTTP request post\"}"; + final String yaml = YAML_BUILDER.newStubbedRequest() + .withMethodGet() + .withUrl("/some/uri") + .withFile(stubbedRequestFile) + .withFoldedPost(expectedPost) + .newStubbedResponse() + .withLiteralBody("OK") + .withStatus("201").build(); + + final ByteArrayOutputStream consoleCaptor = new ByteArrayOutputStream(); + final boolean NO_AUTO_FLUSH = false; + System.setOut(new PrintStream(consoleCaptor, NO_AUTO_FLUSH, StringUtils.UTF_8)); + + unmarshall(yaml); + + System.setOut(System.out); + + final String actualConsoleOutput = consoleCaptor.toString(StringUtils.UTF_8).trim(); + + assertThat(actualConsoleOutput).contains("Could not load file from path: ../../very.big.soap.request.xml"); + assertThat(actualConsoleOutput).contains(YAMLParser.FAILED_TO_LOAD_FILE_ERR); + } + + @Test public void shouldUnmarshall_WhenYAMLValid_WithFileFailedToLoadAndBodySet() throws Exception { @@ -321,6 +353,34 @@ public void shouldUnmarshall_WhenYAMLValid_WithFileFailedToLoadAndBodySet() thro assertThat(StringUtils.newStringUtf8(actualResponse.getResponseBodyAsBytes())).isEqualTo(expectedBody); } + @Test + public void shouldCaptureConsoleErrorOutput_WhenYAMLValid_WithFileFailedToLoadAndBodySet() throws Exception { + + final String stubbedResponseFile = "../../very.big.soap.response.xml"; + + final String expectedBody = "{\"message\", \"Hello, this is HTTP response body\"}"; + final String yaml = YAML_BUILDER.newStubbedRequest() + .withMethodGet() + .withUrl("/some/uri") + .newStubbedResponse() + .withFoldedBody(expectedBody) + .withFile(stubbedResponseFile) + .withStatus("201").build(); + + final ByteArrayOutputStream consoleCaptor = new ByteArrayOutputStream(); + final boolean NO_AUTO_FLUSH = false; + System.setOut(new PrintStream(consoleCaptor, NO_AUTO_FLUSH, StringUtils.UTF_8)); + + unmarshall(yaml); + + System.setOut(System.out); + + final String actualConsoleOutput = consoleCaptor.toString(StringUtils.UTF_8).trim(); + + assertThat(actualConsoleOutput).contains("Could not load file from path: ../../very.big.soap.response.xml"); + assertThat(actualConsoleOutput).contains(YAMLParser.FAILED_TO_LOAD_FILE_ERR); + } + @Test public void shouldUnmarshall_WhenYAMLValid_WithLiteralPost() throws Exception { @@ -732,4 +792,4 @@ public void shouldContainExpectedResourceIdHeaderUponSuccessfulYamlMarshall_When private List unmarshall(final String yaml) throws Exception { return new YAMLParser().parse(".", yaml); } -} \ No newline at end of file +} diff --git a/main/java/io/github/azagniotov/stubby4j/Main.java b/main/java/io/github/azagniotov/stubby4j/Main.java index 70ff4ac93..ed8fa7bc0 100644 --- a/main/java/io/github/azagniotov/stubby4j/Main.java +++ b/main/java/io/github/azagniotov/stubby4j/Main.java @@ -19,6 +19,7 @@ package io.github.azagniotov.stubby4j; +import io.github.azagniotov.stubby4j.cli.ANSITerminal; import io.github.azagniotov.stubby4j.cli.CommandLineInterpreter; import io.github.azagniotov.stubby4j.server.StubbyManager; import io.github.azagniotov.stubby4j.server.StubbyManagerFactory; @@ -39,7 +40,8 @@ import static io.github.azagniotov.stubby4j.utils.FileUtils.BR; public final class Main { - private static final Logger logger = LoggerFactory.getLogger(Main.class); + + private static final Logger LOGGER = LoggerFactory.getLogger(Main.class); private static final ExecutorService EXECUTOR_SERVICE = Executors.newFixedThreadPool(1); private static CommandLineInterpreter commandLineInterpreter; @@ -113,6 +115,7 @@ private static void startStubby4jUsingCommandLineArgs() { final Map commandLineArgs = commandLineInterpreter.getCommandlineParams(); final String configFilename = commandLineArgs.get(CommandLineInterpreter.OPTION_CONFIG); + ANSITerminal.muteConsole(commandLineInterpreter.isMute()); ConsoleUtils.enableDebug(commandLineInterpreter.isDebug()); final File configFile = new File(configFilename); @@ -123,20 +126,14 @@ private static void startStubby4jUsingCommandLineArgs() { stubbyManager.startJetty(); final long totalEnd = System.currentTimeMillis(); - logger.debug("stubby4j successfully started after {} milliseconds.", totalEnd - initialStart); - - stubbyManager.statuses().forEach(logger::debug); + ANSITerminal.status(String.format(BR + "stubby4j successfully started after %s milliseconds", (totalEnd - initialStart)) + BR); + LOGGER.debug("stubby4j successfully started after {} milliseconds.", totalEnd - initialStart); - logger.info("Quit: ctrl-c"); + stubbyManager.statuses().forEach(ANSITerminal::status); + stubbyManager.statuses().forEach(LOGGER::debug); - try { - Class.forName("org.slf4j.impl.StaticLoggerBinder"); - } catch (ClassNotFoundException e) { - System.out.println("\n**********************************************************************************************************************************************"); - System.out.println("*** WARN: stubby4j uses SLF4J. Please provide an SLF4J implementation (i.e. logback, log4j2, etc) in order to enable logging capabilities"); - System.out.println("**********************************************************************************************************************************************"); - System.out.println("\nstubby4j successfully started after " + (totalEnd - initialStart) + " milliseconds.\n"); - } + ANSITerminal.info(BR + "Quit: ctrl-c" + BR); + LOGGER.info("Quit: ctrl-c"); } catch (final Exception ex) { final String msg = diff --git a/main/java/io/github/azagniotov/stubby4j/cli/ANSITerminal.java b/main/java/io/github/azagniotov/stubby4j/cli/ANSITerminal.java index 3d3aec2b1..2f38742dd 100644 --- a/main/java/io/github/azagniotov/stubby4j/cli/ANSITerminal.java +++ b/main/java/io/github/azagniotov/stubby4j/cli/ANSITerminal.java @@ -28,9 +28,12 @@ public final class ANSITerminal { private static final char ESCAPE = 27; private static final String BOLD = String.format("%s[1m", ESCAPE); + private static final String LIGHT_GRAY = String.format("%s[0;37m", ESCAPE); + private static final String GRAY = String.format("%s[1;30m", ESCAPE); private static final String RESET = String.format("%s[0m", ESCAPE); private static final String BLACK = String.format("%s[30m", ESCAPE); private static final String BOLD_BLACK = String.format("%s%s", BOLD, BLACK); + private static final String BOLD_LIGHT_GRAY = String.format("%s%s", BOLD, LIGHT_GRAY); private static final String BLUE = String.format("%s[34m", ESCAPE); private static final String CYAN = String.format("%s[36m", ESCAPE); private static final String GREEN = String.format("%s[32m", ESCAPE); @@ -64,12 +67,12 @@ public static void dump(final String msg) { } /** - * Prints message to the console in black colour + * Prints message to the console in light gray colour * * @param msg message to to print to the console */ public static void status(final String msg) { - print(BOLD_BLACK, msg); + print(BOLD_LIGHT_GRAY, msg); } /** diff --git a/main/java/io/github/azagniotov/stubby4j/filesystem/ExternalFilesScanner.java b/main/java/io/github/azagniotov/stubby4j/filesystem/ExternalFilesScanner.java index 32b6b2c09..74926b37c 100644 --- a/main/java/io/github/azagniotov/stubby4j/filesystem/ExternalFilesScanner.java +++ b/main/java/io/github/azagniotov/stubby4j/filesystem/ExternalFilesScanner.java @@ -1,15 +1,19 @@ package io.github.azagniotov.stubby4j.filesystem; +import io.github.azagniotov.stubby4j.cli.ANSITerminal; import io.github.azagniotov.stubby4j.stubs.StubRepository; import io.github.azagniotov.stubby4j.yaml.YAMLParser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; +import java.util.Date; import java.util.Map; +import static io.github.azagniotov.stubby4j.utils.FileUtils.BR; + public final class ExternalFilesScanner implements Runnable { - private static final Logger logger = LoggerFactory.getLogger(ExternalFilesScanner.class); + private static final Logger LOGGER = LoggerFactory.getLogger(ExternalFilesScanner.class); private final long sleepTime; private final StubRepository stubRepository; @@ -17,7 +21,8 @@ public final class ExternalFilesScanner implements Runnable { public ExternalFilesScanner(final StubRepository stubRepository, final long sleepTime) { this.sleepTime = sleepTime; this.stubRepository = stubRepository; - logger.debug("External file scan enabled, watching external files referenced from {}.", + ANSITerminal.status(String.format("External file scan enabled, watching external files referenced from %s", stubRepository.getYAMLConfigCanonicalPath())); + LOGGER.debug("External file scan enabled, watching external files referenced from {}.", stubRepository.getYAMLConfigCanonicalPath()); } @@ -50,21 +55,25 @@ public void run() { continue; } - logger.info("External file scan detected change in {}.", offendingFilename); + ANSITerminal.info(String.format("%sExternal file scan detected change in %s%s", BR, offendingFilename, BR)); + LOGGER.info("External file scan detected change in {}.", offendingFilename); try { stubRepository.refreshStubsFromYAMLConfig(new YAMLParser()); - logger.info("Successfully performed live refresh of main YAML with external files from: {}.", + + ANSITerminal.ok(String.format("%sSuccessfully performed live refresh of main YAML with external files from: %s on [" + new Date().toString().trim() + "]%s", + BR, stubRepository.getYAMLConfig(), BR)); + LOGGER.info("Successfully performed live refresh of main YAML with external files from: {}.", stubRepository.getYAMLConfig()); } catch (final Exception ex) { - logger.error("Could not refresh YAML configuration.", ex); - logger.warn("YAML refresh aborted, previously loaded stubs remain untouched."); + ANSITerminal.error("Could not refresh YAML configuration, previously loaded stubs remain untouched." + ex.toString()); + LOGGER.error("Could not refresh YAML configuration, previously loaded stubs remain untouched.", ex); } } } catch (final Exception ex) { ex.printStackTrace(); - logger.error("Could not perform live YAML scan.", ex); + LOGGER.error("Could not perform live YAML scan.", ex); } } } \ No newline at end of file diff --git a/main/java/io/github/azagniotov/stubby4j/filesystem/MainYamlScanner.java b/main/java/io/github/azagniotov/stubby4j/filesystem/MainYamlScanner.java index e07f2758b..884f2525a 100644 --- a/main/java/io/github/azagniotov/stubby4j/filesystem/MainYamlScanner.java +++ b/main/java/io/github/azagniotov/stubby4j/filesystem/MainYamlScanner.java @@ -1,14 +1,18 @@ package io.github.azagniotov.stubby4j.filesystem; +import io.github.azagniotov.stubby4j.cli.ANSITerminal; import io.github.azagniotov.stubby4j.stubs.StubRepository; import io.github.azagniotov.stubby4j.yaml.YAMLParser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; +import java.util.Date; + +import static io.github.azagniotov.stubby4j.utils.FileUtils.BR; public final class MainYamlScanner implements Runnable { - private static final Logger logger = LoggerFactory.getLogger(MainYamlScanner.class); + private static final Logger LOGGER = LoggerFactory.getLogger(MainYamlScanner.class); private final long sleepTime; private final StubRepository stubRepository; @@ -16,7 +20,8 @@ public final class MainYamlScanner implements Runnable { public MainYamlScanner(final StubRepository stubRepository, final long sleepTime) { this.sleepTime = sleepTime; this.stubRepository = stubRepository; - logger.debug("Main YAML scan enabled, watching {}.", stubRepository.getYAMLConfigCanonicalPath()); + ANSITerminal.status(String.format("Main YAML scan enabled, watching %s", stubRepository.getYAMLConfigCanonicalPath())); + LOGGER.debug("Main YAML scan enabled, watching {}.", stubRepository.getYAMLConfigCanonicalPath()); } @Override @@ -35,21 +40,25 @@ public void run() { continue; } - logger.info("Main YAML scan detected change in {}.", stubRepository.getYAMLConfigCanonicalPath()); + ANSITerminal.info(String.format("%sMain YAML scan detected change in %s%s", BR, stubRepository.getYAMLConfigCanonicalPath(), BR)); + LOGGER.info("Main YAML scan detected change in {}.", stubRepository.getYAMLConfigCanonicalPath()); try { mainYamlLastModified = currentFileModified; stubRepository.refreshStubsFromYAMLConfig(new YAMLParser()); - logger.info("Successfully performed live refresh of main YAML from: {}.", + + ANSITerminal.ok(String.format("%sSuccessfully performed live refresh of main YAML file from: %s on [" + new Date().toString().trim() + "]%s", + BR, dataYaml.getAbsolutePath(), BR)); + LOGGER.info("Successfully performed live refresh of main YAML from: {}.", dataYaml.getAbsolutePath()); } catch (final Exception ex) { - logger.error("Could not refresh YAML file.", ex); - logger.warn("YAML refresh aborted, in-memory stubs remain untouched."); + ANSITerminal.error("Could not refresh main YAML configuration, in-memory stubs remain untouched." + ex.toString()); + LOGGER.error("Could not refresh main YAML configuration, in-memory stubs remain untouched.", ex); } } } catch (final Exception ex) { - logger.error("Could not perform live YAML scan.", ex); + LOGGER.error("Could not perform live YAML scan.", ex); } } } \ No newline at end of file diff --git a/main/java/io/github/azagniotov/stubby4j/handlers/StubDataRefreshActionHandler.java b/main/java/io/github/azagniotov/stubby4j/handlers/StubDataRefreshActionHandler.java index e41dc08b6..29ee6701c 100644 --- a/main/java/io/github/azagniotov/stubby4j/handlers/StubDataRefreshActionHandler.java +++ b/main/java/io/github/azagniotov/stubby4j/handlers/StubDataRefreshActionHandler.java @@ -19,7 +19,7 @@ package io.github.azagniotov.stubby4j.handlers; -import io.github.azagniotov.stubby4j.server.JettyContext; +import io.github.azagniotov.stubby4j.cli.ANSITerminal; import io.github.azagniotov.stubby4j.stubs.StubRepository; import io.github.azagniotov.stubby4j.utils.ConsoleUtils; import io.github.azagniotov.stubby4j.utils.HandlerUtils; @@ -39,13 +39,11 @@ @SuppressWarnings("serial") public final class StubDataRefreshActionHandler extends AbstractHandler { - private static final Logger logger = LoggerFactory.getLogger(StubDataRefreshActionHandler.class); + private static final Logger LOGGER = LoggerFactory.getLogger(StubDataRefreshActionHandler.class); private final StubRepository stubRepository; - private final JettyContext jettyContext; - public StubDataRefreshActionHandler(final JettyContext newContext, final StubRepository newStubRepository) { - this.jettyContext = newContext; + public StubDataRefreshActionHandler(final StubRepository newStubRepository) { this.stubRepository = newStubRepository; } @@ -66,7 +64,8 @@ public void handle(final String target, final Request baseRequest, final HttpSer final String successMessage = String.format("Successfully performed live refresh of main YAML from: %s on [" + new Date().toString().trim() + "]", stubRepository.getYAMLConfig()); response.getWriter().println(successMessage); - logger.info("Successfully performed live refresh of main YAML from {}.", stubRepository.getYAMLConfig()); + ANSITerminal.ok(successMessage); + LOGGER.info("Successfully performed live refresh of main YAML from {}.", stubRepository.getYAMLConfig()); } catch (final Exception ex) { HandlerUtils.configureErrorResponse(response, HttpStatus.INTERNAL_SERVER_ERROR_500, ex.toString()); } diff --git a/main/java/io/github/azagniotov/stubby4j/http/StubbyHttpTransport.java b/main/java/io/github/azagniotov/stubby4j/http/StubbyHttpTransport.java index 07cd23160..d9025391d 100644 --- a/main/java/io/github/azagniotov/stubby4j/http/StubbyHttpTransport.java +++ b/main/java/io/github/azagniotov/stubby4j/http/StubbyHttpTransport.java @@ -1,7 +1,9 @@ package io.github.azagniotov.stubby4j.http; +import io.github.azagniotov.stubby4j.cli.ANSITerminal; import io.github.azagniotov.stubby4j.client.StubbyResponse; import io.github.azagniotov.stubby4j.stubs.StubRequest; +import io.github.azagniotov.stubby4j.utils.ConsoleUtils; import io.github.azagniotov.stubby4j.utils.StringUtils; import org.eclipse.jetty.http.HttpMethod; import org.eclipse.jetty.http.HttpStatus; @@ -33,7 +35,7 @@ * @since 11/4/12, 11:03 AM */ public class StubbyHttpTransport { - private static final Logger logger = LoggerFactory.getLogger(StubbyHttpTransport.class); + private static final Logger LOGGER = LoggerFactory.getLogger(StubbyHttpTransport.class); private static final Set SUPPORTED_METHODS = new HashSet() {{ add(HttpMethod.GET.asString()); @@ -51,7 +53,11 @@ public StubbyHttpTransport() { public StubbyResponse fetchRecordableHTTPResponse(final StubRequest request, final String recordingSource) throws IOException { final String method = request.getMethod().get(0); - logger.debug("Recording HTTP response using {} [{}].", method, recordingSource); + if (!ANSITerminal.isMute()) { + final String logMessage = String.format("[%s] -> Recording HTTP response using %s [%s]", ConsoleUtils.getTime(), method, recordingSource); + ANSITerminal.incoming(logMessage); + } + LOGGER.debug("Recording HTTP response using {} [{}].", method, recordingSource); return getResponse(method, recordingSource, request.getPostBody(), diff --git a/main/java/io/github/azagniotov/stubby4j/server/JettyFactory.java b/main/java/io/github/azagniotov/stubby4j/server/JettyFactory.java index ce93c6f9e..3ef4d7abf 100644 --- a/main/java/io/github/azagniotov/stubby4j/server/JettyFactory.java +++ b/main/java/io/github/azagniotov/stubby4j/server/JettyFactory.java @@ -114,7 +114,7 @@ private ContextHandlerCollection constructHandlers() { constructHandler(SSL_CONNECTOR_NAME, ROOT_PATH_INFO, gzipHandler(new StubsPortalHandler(stubRepository))), constructHandler(ADMIN_CONNECTOR_NAME, "/status", gzipHandler(new StatusPageHandler(jettyContext, stubRepository))), - constructHandler(ADMIN_CONNECTOR_NAME, "/refresh", new StubDataRefreshActionHandler(jettyContext, stubRepository)), + constructHandler(ADMIN_CONNECTOR_NAME, "/refresh", new StubDataRefreshActionHandler(stubRepository)), constructHandler(ADMIN_CONNECTOR_NAME, "/js/highlight", gzipHandler(staticResourceHandler("ui/js/highlight/"))), constructHandler(ADMIN_CONNECTOR_NAME, "/js/minified", gzipHandler(staticResourceHandler("ui/js/minified/"))), constructHandler(ADMIN_CONNECTOR_NAME, "/js/d3", gzipHandler(staticResourceHandler("ui/js/d3/"))), diff --git a/main/java/io/github/azagniotov/stubby4j/server/StubbyManager.java b/main/java/io/github/azagniotov/stubby4j/server/StubbyManager.java index 77ded4b54..fc5b79880 100644 --- a/main/java/io/github/azagniotov/stubby4j/server/StubbyManager.java +++ b/main/java/io/github/azagniotov/stubby4j/server/StubbyManager.java @@ -20,6 +20,7 @@ package io.github.azagniotov.stubby4j.server; +import io.github.azagniotov.stubby4j.cli.ANSITerminal; import io.github.azagniotov.stubby4j.stubs.StubRepository; import org.eclipse.jetty.server.Server; import org.slf4j.Logger; @@ -28,7 +29,7 @@ import java.util.List; public final class StubbyManager { - private static final Logger logger = LoggerFactory.getLogger(StubbyManager.class); + private static final Logger LOGGER = LoggerFactory.getLogger(StubbyManager.class); private final Server server; private final JettyFactory jettyFactory; @@ -47,7 +48,8 @@ public synchronized void startJetty() throws Exception { server.start(); while (!isJettyUp()) { - logger.warn("Waiting for Jetty to finish starting up.."); + ANSITerminal.warn("Waiting for Jetty to finish starting up.."); + LOGGER.warn("Waiting for Jetty to finish starting up.."); Thread.sleep(250); } stubRepository.retrieveLoadedStubs(); @@ -61,10 +63,13 @@ public synchronized void stopJetty() throws Exception { server.stop(); while (!isJettyDown()) { - logger.warn("Waiting for Jetty to finish shutting down.."); + ANSITerminal.warn("Waiting for Jetty to finish shutting down.."); + LOGGER.warn("Waiting for Jetty to finish shutting down.."); Thread.sleep(250); } - logger.info("Jetty successfully shutdown."); + + ANSITerminal.status("Jetty successfully shutdown"); + LOGGER.info("Jetty successfully shutdown."); } public synchronized void joinJetty() throws Exception { diff --git a/main/java/io/github/azagniotov/stubby4j/server/StubbyManagerFactory.java b/main/java/io/github/azagniotov/stubby4j/server/StubbyManagerFactory.java index b52a485ef..0ae0a01a9 100644 --- a/main/java/io/github/azagniotov/stubby4j/server/StubbyManagerFactory.java +++ b/main/java/io/github/azagniotov/stubby4j/server/StubbyManagerFactory.java @@ -19,6 +19,7 @@ package io.github.azagniotov.stubby4j.server; +import io.github.azagniotov.stubby4j.cli.ANSITerminal; import io.github.azagniotov.stubby4j.cli.CommandLineInterpreter; import io.github.azagniotov.stubby4j.cli.EmptyLogger; import io.github.azagniotov.stubby4j.filesystem.ExternalFilesScanner; @@ -57,6 +58,10 @@ public synchronized StubbyManager construct(final File configFile, watchDataStore(stubRepository, watchScanTime); } + if (commandLineArgs.containsKey(CommandLineInterpreter.OPTION_MUTE)) { + ANSITerminal.muteConsole(true); + } + return new StubbyManager(server, jettyFactory, stubRepository); } diff --git a/main/java/io/github/azagniotov/stubby4j/stubs/StubMatcher.java b/main/java/io/github/azagniotov/stubby4j/stubs/StubMatcher.java index 1735ac7bc..639ec6509 100644 --- a/main/java/io/github/azagniotov/stubby4j/stubs/StubMatcher.java +++ b/main/java/io/github/azagniotov/stubby4j/stubs/StubMatcher.java @@ -2,6 +2,7 @@ import io.github.azagniotov.stubby4j.annotations.VisibleForTesting; +import io.github.azagniotov.stubby4j.cli.ANSITerminal; import org.custommonkey.xmlunit.Diff; import org.custommonkey.xmlunit.ElementNameAndAttributeQualifier; import org.json.JSONException; @@ -27,7 +28,7 @@ import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.URL; class StubMatcher { - private static final Logger logger = LoggerFactory.getLogger(StubMatcher.class); + private static final Logger LOGGER = LoggerFactory.getLogger(StubMatcher.class); private final Map regexGroups; private static final Pattern SUB_TYPE_PATTERN = Pattern.compile("/(?:.*\\+)?(\\w*);?"); @@ -38,34 +39,44 @@ class StubMatcher { boolean matches(final StubRequest stubbedRequest, final StubRequest assertingRequest) { if (!urlsMatch(stubbedRequest.getUri(), assertingRequest.getUri())) { - logger.error("Failed to match on URL [{}] WITH [{}].", stubbedRequest.getUri(), assertingRequest.getUri()); + ANSITerminal.error(String.format("Failed to match on URL [%s] WITH [%s]", stubbedRequest.getUri(), assertingRequest.getUri())); + LOGGER.error("Failed to match on URL [{}] WITH [{}].", stubbedRequest.getUri(), assertingRequest.getUri()); return false; } - logger.info("Matched on URL [%s] WITH [%s].", stubbedRequest.getUri(), assertingRequest.getUri()); + ANSITerminal.info(String.format("Matched on URL [%s] WITH [%s]", stubbedRequest.getUri(), assertingRequest.getUri())); + LOGGER.info("Matched on URL [%s] WITH [%s].", stubbedRequest.getUri(), assertingRequest.getUri()); if (!listsIntersect(stubbedRequest.getMethod(), assertingRequest.getMethod())) { - logger.error("Failed to match on METHOD [{}] WITH [{}].", stubbedRequest.getMethod(), assertingRequest.getMethod()); + ANSITerminal.error(String.format("Failed to match on METHOD [%s] WITH [%s]", stubbedRequest.getMethod(), assertingRequest.getMethod())); + LOGGER.error("Failed to match on METHOD [{}] WITH [{}].", stubbedRequest.getMethod(), assertingRequest.getMethod()); return false; } - logger.info("Matched on METHOD [{}] WITH [{}]", stubbedRequest.getMethod(), assertingRequest.getMethod()); + ANSITerminal.info(String.format("Matched on METHOD [%s] WITH [%s]", stubbedRequest.getMethod(), assertingRequest.getMethod())); + LOGGER.info("Matched on METHOD [{}] WITH [{}]", stubbedRequest.getMethod(), assertingRequest.getMethod()); if (!postBodiesMatch(stubbedRequest.isPostStubbed(), stubbedRequest.getPostBody(), assertingRequest)) { - logger.error("Failed to match on POST BODY [{}] WITH [{}].", stubbedRequest.getPostBody(), assertingRequest.getPostBody()); + ANSITerminal.error(String.format("Failed to match on POST BODY [%s] WITH [%s]", stubbedRequest.getPostBody(), assertingRequest.getPostBody())); + LOGGER.error("Failed to match on POST BODY [{}] WITH [{}].", stubbedRequest.getPostBody(), assertingRequest.getPostBody()); return false; } - logger.info("Matched on POST BODY [{}] WITH [{}].", stubbedRequest.getPostBody(), assertingRequest.getPostBody()); + ANSITerminal.info(String.format("Matched on POST BODY [%s] WITH [%s]", stubbedRequest.getPostBody(), assertingRequest.getPostBody())); + LOGGER.info("Matched on POST BODY [{}] WITH [{}].", stubbedRequest.getPostBody(), assertingRequest.getPostBody()); if (!headersMatch(stubbedRequest.getHeaders(), assertingRequest.getHeaders())) { - logger.error("Failed to match on HEADERS [{}] WITH [{}].", stubbedRequest.getHeaders(), assertingRequest.getHeaders()); + ANSITerminal.error(String.format("Failed to match on HEADERS [%s] WITH [%s]", stubbedRequest.getHeaders(), assertingRequest.getHeaders())); + LOGGER.error("Failed to match on HEADERS [{}] WITH [{}].", stubbedRequest.getHeaders(), assertingRequest.getHeaders()); return false; } - logger.info("Matched on HEADERS [{}] WITH [{}].", stubbedRequest.getHeaders(), assertingRequest.getHeaders()); + ANSITerminal.info(String.format("Matched on HEADERS [%s] WITH [%s]", stubbedRequest.getHeaders(), assertingRequest.getHeaders())); + LOGGER.info("Matched on HEADERS [{}] WITH [{}].", stubbedRequest.getHeaders(), assertingRequest.getHeaders()); if (!queriesMatch(stubbedRequest.getQuery(), assertingRequest.getQuery())) { - logger.error("Failed to match on QUERY [{}] WITH [{}].", stubbedRequest.getQuery(), assertingRequest.getQuery()); + ANSITerminal.error(String.format("Failed to match on QUERY [%s] WITH [%s]", stubbedRequest.getQuery(), assertingRequest.getQuery())); + LOGGER.error("Failed to match on QUERY [{}] WITH [{}].", stubbedRequest.getQuery(), assertingRequest.getQuery()); return false; } - logger.info("Matched on QUERY [{}] WITH [{}].", stubbedRequest.getQuery(), assertingRequest.getQuery()); + ANSITerminal.info(String.format("Matched on QUERY [%s] WITH [%s]", stubbedRequest.getQuery(), assertingRequest.getQuery())); + LOGGER.info("Matched on QUERY [{}] WITH [{}].", stubbedRequest.getQuery(), assertingRequest.getQuery()); return true; } diff --git a/main/java/io/github/azagniotov/stubby4j/stubs/StubRepository.java b/main/java/io/github/azagniotov/stubby4j/stubs/StubRepository.java index 8faa3c78d..8d8141bd3 100644 --- a/main/java/io/github/azagniotov/stubby4j/stubs/StubRepository.java +++ b/main/java/io/github/azagniotov/stubby4j/stubs/StubRepository.java @@ -1,6 +1,7 @@ package io.github.azagniotov.stubby4j.stubs; import io.github.azagniotov.stubby4j.annotations.CoberturaIgnore; +import io.github.azagniotov.stubby4j.cli.ANSITerminal; import io.github.azagniotov.stubby4j.client.StubbyResponse; import io.github.azagniotov.stubby4j.http.StubbyHttpTransport; import io.github.azagniotov.stubby4j.utils.FileUtils; @@ -40,7 +41,7 @@ import static java.util.Collections.list; public class StubRepository { - private static final Logger logger = LoggerFactory.getLogger(StubRepository.class); + private static final Logger LOGGER = LoggerFactory.getLogger(StubRepository.class); private final File configFile; private final List stubs; @@ -112,7 +113,8 @@ private StubResponse findMatch(final StubHttpLifecycle incomingRequest) { final StubbyResponse stubbyResponse = stubbyHttpTransport.fetchRecordableHTTPResponse(matchedStub.getRequest(), recordingSource); injectObjectFields(matchedStubResponse, BODY.toString(), stubbyResponse.getContent()); } catch (Exception e) { - logger.error("Could not record from {}.", e); + ANSITerminal.error(String.format("Could not record from %s: %s", recordingSource, e.toString())); + LOGGER.error("Could not record from {}.", e); } } return matchedStubResponse; @@ -146,17 +148,22 @@ private synchronized Optional matchStub(final StubHttpLifecyc final long initialStart = System.currentTimeMillis(); final String incomingRequestUrl = incomingStub.getUrl(); if (matchedStubsCache.containsKey(incomingRequestUrl)) { - logger.debug("Local cache contains potential match for the URL [{}].", incomingRequestUrl); + ANSITerminal.loaded(String.format("Local cache contains potential match for the URL [%s]", incomingRequestUrl)); + LOGGER.debug("Local cache contains potential match for the URL [{}].", incomingRequestUrl); final StubHttpLifecycle cachedPotentialMatch = matchedStubsCache.get(incomingRequestUrl); + // The order(?) in which equality is determined is important here (what object is "equal to" the other one) if (incomingStub.equals(cachedPotentialMatch)) { final long elapsed = System.currentTimeMillis() - initialStart; logMatch(elapsed, cachedPotentialMatch); - logger.debug("Potential match for the URL [{}] was deemed as a full match.", incomingRequestUrl); + ANSITerminal.loaded(String.format("Potential match for the URL [%s] was deemed as a full match", incomingRequestUrl)); + LOGGER.debug("Potential match for the URL [{}] was deemed as a full match.", incomingRequestUrl); return Optional.of(cachedPotentialMatch); } - logger.warn("Cached match for the URL [{}] failed to match fully, invalidating match cache.", incomingRequestUrl); + ANSITerminal.warn(String.format("Cached match for the URL [%s] failed to match fully, invalidating match cache..", incomingRequestUrl)); + LOGGER.warn("Cached match for the URL [{}] failed to match fully, invalidating match cache.", incomingRequestUrl); + matchedStubsCache.remove(incomingRequestUrl); } @@ -165,7 +172,9 @@ private synchronized Optional matchStub(final StubHttpLifecyc if (incomingStub.equals(stubbed)) { final long elapsed = System.currentTimeMillis() - initialStart; logMatch(elapsed, stubbed); - logger.debug("Caching the found match for URL [{}].", incomingRequestUrl); + + ANSITerminal.status(String.format("Caching the found match for URL [%s]", incomingRequestUrl)); + LOGGER.debug("Caching the found match for URL [{}].", incomingRequestUrl); matchedStubsCache.put(incomingRequestUrl, stubbed); return Optional.of(stubbed); @@ -188,7 +197,9 @@ private static void logMatch(long elapsed, StubHttpLifecycle matched) { .append(matched.getDescription()) .append("]"); } - logger.debug("{}", message); + + ANSITerminal.status(message.toString()); + LOGGER.debug("{}", message); } public synchronized Optional matchStubByIndex(final int index) { diff --git a/main/java/io/github/azagniotov/stubby4j/utils/ConsoleUtils.java b/main/java/io/github/azagniotov/stubby4j/utils/ConsoleUtils.java index bf3f7e8a4..b90c7dec9 100644 --- a/main/java/io/github/azagniotov/stubby4j/utils/ConsoleUtils.java +++ b/main/java/io/github/azagniotov/stubby4j/utils/ConsoleUtils.java @@ -20,6 +20,7 @@ package io.github.azagniotov.stubby4j.utils; import io.github.azagniotov.stubby4j.annotations.CoberturaIgnore; +import io.github.azagniotov.stubby4j.cli.ANSITerminal; import io.github.azagniotov.stubby4j.stubs.StubHttpLifecycle; import io.github.azagniotov.stubby4j.stubs.StubRequest; import org.eclipse.jetty.http.HttpStatus; @@ -31,6 +32,7 @@ import java.util.Calendar; import java.util.Locale; +import static io.github.azagniotov.stubby4j.utils.FileUtils.BR; import static io.github.azagniotov.stubby4j.utils.StringUtils.isSet; /** @@ -38,7 +40,9 @@ * @since 10/26/12, 1:00 PM */ public final class ConsoleUtils { - private static final Logger logger = LoggerFactory.getLogger(ConsoleUtils.class); + + private static final Logger LOGGER = LoggerFactory.getLogger(ConsoleUtils.class); + private static boolean debug = false; private ConsoleUtils() { @@ -55,14 +59,18 @@ public static void logIncomingRequestError(final HttpServletRequest request, fin request.getRequestURI(), error ); - logger.error(logMessage); + ANSITerminal.error(logMessage); + LOGGER.error(logMessage); } @CoberturaIgnore private static void logRawIncomingRequest(final HttpServletRequest request) { - logger.debug(" ***** [DEBUG INCOMING RAW HTTP REQUEST DUMP] ***** "); - logger.debug(HttpRequestUtils.dump(request)); - logger.debug(" ***** [DEBUG INCOMING RAW HTTP REQUEST DUMP] ***** "); + ANSITerminal.warn(" ***** [DEBUG INCOMING RAW HTTP REQUEST DUMP] ***** "); + ANSITerminal.info(HttpRequestUtils.dump(request)); + ANSITerminal.warn(" ***** [DEBUG INCOMING RAW HTTP REQUEST DUMP] ***** " + BR); + LOGGER.debug(" ***** [DEBUG INCOMING RAW HTTP REQUEST DUMP] ***** "); + LOGGER.debug(HttpRequestUtils.dump(request)); + LOGGER.debug(" ***** [DEBUG INCOMING RAW HTTP REQUEST DUMP] ***** "); } @CoberturaIgnore @@ -73,16 +81,23 @@ public static void logIncomingRequest(final HttpServletRequest request) { request.getMethod(), request.getRequestURI() ); + ANSITerminal.incoming(logMessage); + if (debug) { - logger.debug(logMessage); + ConsoleUtils.logRawIncomingRequest(request); } } @CoberturaIgnore public static void logAssertingRequest(final StubRequest assertingStubRequest) { - logger.debug(" ***** [DEBUG INCOMING ASSERTING HTTP REQUEST DUMP] ***** "); - logger.debug("{}", assertingStubRequest); - logger.debug(" ***** [DEBUG INCOMING ASSERTING HTTP REQUEST DUMP] ***** "); + if (debug) { + ANSITerminal.warn(" ***** [DEBUG INCOMING ASSERTING HTTP REQUEST DUMP] ***** "); + ANSITerminal.info(assertingStubRequest.toString()); + ANSITerminal.warn(" ***** [DEBUG INCOMING ASSERTING HTTP REQUEST DUMP] ***** " + BR); + LOGGER.debug(" ***** [DEBUG INCOMING ASSERTING HTTP REQUEST DUMP] ***** "); + LOGGER.debug("{}", assertingStubRequest); + LOGGER.debug(" ***** [DEBUG INCOMING ASSERTING HTTP REQUEST DUMP] ***** "); + } } @CoberturaIgnore @@ -96,16 +111,21 @@ public static void logOutgoingResponse(final String url, final HttpServletRespon HttpStatus.getMessage(status) ); - if (status >= HttpStatus.BAD_REQUEST_400) { - logger.error(logMessage); - } else if (status >= HttpStatus.MULTIPLE_CHOICES_300) { - logger.warn(logMessage); - } else if (status >= HttpStatus.OK_200) { - logger.info(logMessage); - } else if (status >= HttpStatus.CONTINUE_100) { - logger.info(logMessage); + if (HttpStatus.isServerError(status) || HttpStatus.isClientError(status)) { + ANSITerminal.error(logMessage); + LOGGER.error(logMessage); + } else if (HttpStatus.isRedirection(status)) { + ANSITerminal.warn(logMessage); + LOGGER.warn(logMessage); + } else if (HttpStatus.isSuccess(status)) { + ANSITerminal.ok(logMessage); + LOGGER.info(logMessage); + } else if (HttpStatus.isInformational(status)) { + ANSITerminal.info(logMessage); + LOGGER.info(logMessage); } else { - logger.debug(logMessage); + ANSITerminal.log(logMessage); + LOGGER.debug(logMessage); } } @@ -121,7 +141,7 @@ public static void logUnmarshalledStub(final StubHttpLifecycle lifecycle) { loadedMsgBuilder.append(String.format(" [%s]", lifecycle.getDescription())); } - logger.debug("{}", loadedMsgBuilder); + ANSITerminal.loaded(loadedMsgBuilder.toString()); } @CoberturaIgnore diff --git a/main/java/io/github/azagniotov/stubby4j/yaml/YAMLParser.java b/main/java/io/github/azagniotov/stubby4j/yaml/YAMLParser.java index fac9b8d0e..2ef3d1a6d 100644 --- a/main/java/io/github/azagniotov/stubby4j/yaml/YAMLParser.java +++ b/main/java/io/github/azagniotov/stubby4j/yaml/YAMLParser.java @@ -20,6 +20,7 @@ package io.github.azagniotov.stubby4j.yaml; import io.github.azagniotov.stubby4j.annotations.CoberturaIgnore; +import io.github.azagniotov.stubby4j.cli.ANSITerminal; import io.github.azagniotov.stubby4j.stubs.AbstractBuilder; import io.github.azagniotov.stubby4j.stubs.ReflectableStub; import io.github.azagniotov.stubby4j.stubs.StubHttpLifecycle; @@ -66,7 +67,7 @@ import static org.yaml.snakeyaml.DumperOptions.FlowStyle; public class YAMLParser { - Logger logger = LoggerFactory.getLogger(YAMLParser.class); + private static final Logger LOGGER = LoggerFactory.getLogger(YAMLParser.class); static final String FAILED_TO_LOAD_FILE_ERR = "Failed to retrieveLoadedStubs response content using relative path specified in 'file'. Check that response content exists in relative path specified in 'file'"; private final static Yaml SNAKE_YAML = SnakeYaml.INSTANCE.getSnakeYaml(); @@ -238,7 +239,8 @@ private Optional loadFileContentFromFileUrl(final Object configPropertyN return ofNullable(uriToFile(dataConfigHomeDirectory, filePath)); } catch (final IOException ex) { - logger.error(FAILED_TO_LOAD_FILE_ERR, ex); + ANSITerminal.error(ex.getMessage() + " " + FAILED_TO_LOAD_FILE_ERR); + LOGGER.error(FAILED_TO_LOAD_FILE_ERR, ex); } return Optional.empty();