Skip to content

Commit

Permalink
feat: use console logger and verbose mode (#309)
Browse files Browse the repository at this point in the history
  • Loading branch information
manikmagar committed Nov 11, 2022
1 parent 49dee9f commit d8db401
Show file tree
Hide file tree
Showing 11 changed files with 213 additions and 98 deletions.
5 changes: 1 addition & 4 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ plugins {
id "org.gradle.crypto.checksum" version "1.4.0"
id "com.github.breadmoirai.github-release" version "2.2.12"
id "de.fuerstenau.buildconfig" version "1.1.8"
id "com.adarshr.test-logger" version "2.1.1"
id "com.geoffgranum.gradle-conventional-changelog" version "0.3.1"
id "org.sonarqube" version "3.3"
id "jacoco"
Expand Down Expand Up @@ -50,15 +49,13 @@ jacocoTestReport {

dependencies {
implementation 'guru.nidi:graphviz-java-all-j2v8:0.17.0'
implementation 'ch.qos.logback:logback-classic:1.2.9'
implementation 'info.picocli:picocli:4.6.3'
implementation 'org.slf4j:slf4j-nop:1.7.30'
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.9.1'
testImplementation 'org.junit.jupiter:junit-jupiter-engine:5.9.1'
testImplementation 'org.junit.jupiter:junit-jupiter-params:5.9.1'
testImplementation 'org.assertj:assertj-core:3.23.1'
testImplementation 'org.mockito:mockito-inline:4.8.1'
testImplementation 'io.github.netmikey.logunit:logunit-core:1.1.3'
testImplementation 'io.github.netmikey.logunit:logunit-logback:1.1.3'
}

spotless {
Expand Down
52 changes: 23 additions & 29 deletions src/main/java/com/javastreets/mulefd/DiagramRenderer.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.javastreets.mulefd;

import static com.javastreets.mulefd.util.ConsoleLog.*;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
Expand All @@ -8,9 +10,6 @@
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.javastreets.mulefd.cli.CommandModel;
import com.javastreets.mulefd.cli.Configuration;
import com.javastreets.mulefd.drawings.Diagram;
Expand All @@ -30,9 +29,7 @@ public class DiagramRenderer {
public static final int EXPECTED_NUMBER_OF_COLUMNS = 6;
public static final String ERROR_MESSAGE_INVALID_NUMBER_OF_COLUMNS =
"Found an invalid configuration line in mule components file. Column count must be "
+ EXPECTED_NUMBER_OF_COLUMNS + ". Line - {}";
Logger log = LoggerFactory.getLogger(DiagramRenderer.class);

+ EXPECTED_NUMBER_OF_COLUMNS + ". Line - %s";
private final CommandModel commandModel;

public DiagramRenderer(CommandModel commandModel) {
Expand Down Expand Up @@ -80,7 +77,7 @@ Map<String, ComponentItem> prepareKnownComponents() throws MuleFDException {
* @param filePath {@link Path} to read components from
*/
private void loadComponentsFile(final Map<String, ComponentItem> items, final Path filePath) {
log.debug("Loading known components from {}", filePath);
info("Loading known components from %s", filePath);
Validations.requireTrue(Files.exists(filePath),
"Configuration components file '" + filePath + "' does not exist");
try {
Expand All @@ -94,19 +91,19 @@ private void loadComponentsFile(final Map<String, ComponentItem> items, InputStr
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream))) {
for (String line; (line = bufferedReader.readLine()) != null;) {
if (!line.startsWith("prefix")) {
log.trace("Reading component line - {}", line);
debug("Reading component line - %s", line);
String[] part = line.split(",");
if (part.length != EXPECTED_NUMBER_OF_COLUMNS) {
log.error(ERROR_MESSAGE_INVALID_NUMBER_OF_COLUMNS, line);
error(ERROR_MESSAGE_INVALID_NUMBER_OF_COLUMNS, line);
throw new DrawingException("Invalid mule components configuration file.");
}
ComponentItem item = new ComponentItem();
item.setPrefix(part[0]);
item.setOperation(part[1]);
item.setSource(Boolean.parseBoolean(part[2]));
if (item.getOperation().equals("*") && item.isSource()) {
log.error(
"Wildcard operation entry as a source is not allowed. Please create a separate entry for source if needed. Line - {}",
error(
"Wildcard operation entry as a source is not allowed. Please create a separate entry for source if needed. Line - %s",
line);
throw new DrawingException("Invalid mule components configuration file.");
}
Expand All @@ -133,7 +130,7 @@ public Boolean render() {
}
return diagram(context);
} catch (IOException e) {
log.error("Error while parsing xml file", e);
error("Error while parsing xml file", e);
return false;
}
}
Expand Down Expand Up @@ -161,62 +158,59 @@ Path getMuleSourcePath() {
Path newSourcePath = commandModel.getSourcePath();
commandModel.setMuleVersion(MULE_VERSION_4);
if (Files.isDirectory(commandModel.getSourcePath())) {
log.debug("Source is a directory {}", commandModel.getSourcePath());
debug("Source is a directory %s", commandModel.getSourcePath());
if (existInSource("src/main/mule/") && existInSource("mule-artifact.json")) {
log.info(
"Found standard Mule 4 source structure 'src/main/mule'. Source is a Mule-4 project.");
info("Found standard Mule 4 source structure 'src/main/mule'. Source is a Mule-4 project.");
newSourcePath = Paths.get(commandModel.getSourcePath().toString(), "src/main/mule");
commandModel.setMuleVersion(MULE_VERSION_4);
} else if (existInSource("src/main/app/") && existInSource("mule-project.xml")) {
log.info(
"Found standard Mule 3 source structure 'src/main/app'. Source is a Mule-3 project.");
info("Found standard Mule 3 source structure 'src/main/app'. Source is a Mule-3 project.");
newSourcePath = Paths.get(commandModel.getSourcePath().toString(), "src/main/app");
commandModel.setMuleVersion(MULE_VERSION_3);
} else {
log.warn(
warn(
"No known standard Mule (3/4) directory structure found (src/main/mule or src/main/app).");
}
log.info(
"Source directory '{}' will be scanned recursively to find Mule {} configuration files.",
info("Source directory '%s' will be scanned recursively to find Mule %s configuration files.",
newSourcePath, commandModel.getMuleVersion());
} else {
log.info("Reading source file {}", newSourcePath);
info("Reading source file %s", newSourcePath);
}
return newSourcePath;
}

void flows(List<FlowContainer> flows, Map<String, ComponentItem> knownComponents, Path path) {
log.debug("Reading file {}", path);
debug("Reading file %s", path);
MuleXmlParser muleXmlParser = new MuleXmlParser(path.toAbsolutePath().toString());
muleXmlParser.parse();
if (muleXmlParser.isMuleFile()) {
flows.addAll(muleXmlParser.getMuleFlows(knownComponents));
} else {
log.debug("Not a mule configuration file: {}", path);
debug("Not a mule configuration file: %s", path);
}
}

Boolean diagram(DrawingContext context) {
if (context.getComponents().isEmpty()) {
log.warn("No mule flows found for creating diagram.");
warn("No mule flows found for creating diagram.");
return false;
}
ServiceLoader<Diagram> diagramServices = ServiceLoader.load(Diagram.class);
Iterator<Diagram> its = diagramServices.iterator();
boolean drawn = false;
while (its.hasNext()) {
Diagram diagram = its.next();
log.debug("Analyzing diagram provider {}", diagram.getClass());
debug("Analyzing diagram provider %s", diagram.getClass());
if (diagram.supports(commandModel.getDiagramType())) {
log.debug("Found a supporting provider {} for drawing {}", diagram.getClass(),
debug("Found a supporting provider %s for drawing %s", diagram.getClass(),
commandModel.getDiagramType());
log.info("Initiating drawing {} at {}", diagram.name(), commandModel.getTargetPath());
info("Initiating drawing %s at %s", diagram.name(), commandModel.getTargetPath());
if (context.getFlowName() != null) {
log.info("Generating diagram for dependencies of single flow only - {}",
info("Generating diagram for dependencies of single flow only - %s",
context.getFlowName());
}
drawn = diagram.draw(context);
log.info("Generated {} at {}", diagram.name(), context.getOutputFile().getAbsolutePath());
info("Generated %s at %s", diagram.name(), context.getOutputFile().getAbsolutePath());
break;
}
}
Expand Down
7 changes: 7 additions & 0 deletions src/main/java/com/javastreets/mulefd/cli/BaseCommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import java.util.concurrent.Callable;

import com.javastreets.mulefd.util.ConsoleLog;

import picocli.CommandLine;

public abstract class BaseCommand implements Callable<Integer> {
Expand All @@ -15,8 +17,13 @@ public abstract class BaseCommand implements Callable<Integer> {
description = "display this help message")
boolean usageHelpRequested;

@CommandLine.Option(names = {"-v", "--verbose"}, description = "Run in verbose mode")
boolean verboseMode;

@Override
public Integer call() throws Exception {
if (verboseMode)
ConsoleLog.setVerbose(true);
return execute();
}

Expand Down
10 changes: 5 additions & 5 deletions src/main/java/com/javastreets/mulefd/cli/Configuration.java
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
package com.javastreets.mulefd.cli;

import static com.javastreets.mulefd.util.ConsoleLog.debug;
import static com.javastreets.mulefd.util.ConsoleLog.warn;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Configuration {
protected final Properties properties = new Properties();
Expand All @@ -17,7 +18,6 @@ public class Configuration {

public static final String MULEFD_CONFIG_PROPERTIES = "mulefd.properties";

private static final Logger log = LoggerFactory.getLogger(Configuration.class);

private static final Configuration globalConfig = readUserHomeConfig();
private static final Configuration defaultConfig = readDefaultConfig();
Expand Down Expand Up @@ -120,7 +120,7 @@ private static Configuration readUserHomeConfig() {
Paths.get(userHome).resolve(MULEFD_DOT_DIRECTORY).resolve(MULEFD_CONFIG_PROPERTIES);
if (!configProperties.toFile().exists())
return new Configuration();
log.debug("Loading default properties file from: {}", configProperties);
debug("Loading default properties file from: {}", configProperties);
return read(configProperties);
}

Expand All @@ -138,7 +138,7 @@ public static Configuration read(Path configFile) {
props.load(in);
configuration.properties.putAll(props);
} catch (IOException e) {
log.warn("Couldn't parse configuration: {}", configFile);
warn("Couldn't parse configuration: {}", configFile);
}
}
return configuration;
Expand Down
10 changes: 4 additions & 6 deletions src/main/java/com/javastreets/mulefd/cli/DiagramBaseCommand.java
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
package com.javastreets.mulefd.cli;

import static com.javastreets.mulefd.util.ConsoleLog.info;

import java.nio.file.Files;
import java.nio.file.Path;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.javastreets.mulefd.DiagramRenderer;
import com.javastreets.mulefd.drawings.DiagramType;
import com.javastreets.mulefd.util.DateUtil;
Expand All @@ -15,7 +14,6 @@

public abstract class DiagramBaseCommand extends BaseCommand {

private static final Logger log = LoggerFactory.getLogger(DiagramBaseCommand.class);
@CommandLine.Parameters(index = "0",
description = "Source directory path containing mule configuration files")
private Path sourcePath;
Expand All @@ -40,11 +38,11 @@ public abstract class DiagramBaseCommand extends BaseCommand {

@Override
protected Integer execute() {
log.info("Mule Flow Diagrams - {}, Started at {}", Version.VersionProvider.getMuleFDVersion(),
info("Mule Flow Diagrams - %s, Started at %s", Version.VersionProvider.getMuleFDVersion(),
DateUtil.now());
CommandModel cm = getCommandModel();
Boolean rendered = new DiagramRenderer(cm).render();
log.info("Finished at {}", DateUtil.now());
info("Finished at %s", DateUtil.now());
return EXIT_OK;
}

Expand Down
24 changes: 10 additions & 14 deletions src/main/java/com/javastreets/mulefd/drawings/GraphDiagram.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.javastreets.mulefd.drawings;

import static com.javastreets.mulefd.util.ConsoleLog.*;
import static com.javastreets.mulefd.util.FileUtil.sanitizeFilename;
import static guru.nidi.graphviz.attribute.Arrow.DirType;
import static guru.nidi.graphviz.attribute.Arrow.VEE;
Expand All @@ -15,9 +16,6 @@
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.javastreets.mulefd.cli.Configuration;
import com.javastreets.mulefd.drawings.engine.GraphvizEngineHelper;
import com.javastreets.mulefd.model.Component;
Expand All @@ -34,8 +32,6 @@

public class GraphDiagram implements Diagram {

Logger log = LoggerFactory.getLogger(GraphDiagram.class);

@Override
public boolean draw(DrawingContext drawingContext) {
MutableGraph rootGraph = initNewGraphWithLegend(true);
Expand Down Expand Up @@ -108,7 +104,7 @@ MutableNode sizedNode(String label, double width) {
}

void addLegends(MutableGraph rootGraph) {
log.debug("Adding legend to graph - {}", rootGraph.name());
debug("Adding legend to graph - %s", rootGraph.name());
graph("legend").directed().cluster().graphAttr().with(Label.html("<b>Legend</b>"), Style.DASHED)
.with(
asFlow(sizedNode("flow", 1))
Expand Down Expand Up @@ -138,25 +134,25 @@ boolean writeFlowGraph(Component flowComponent, Path targetDirectory, MutableGra
String flowName = flowComponent.getName();
Path targetPath =
Paths.get(targetDirectory.toString(), sanitizeFilename(flowName.concat(".png")));
log.info("Writing individual flow graph for {} at {}", flowName, targetPath);
info("Writing individual flow graph for %s at %s", flowName, targetPath);
try {
flowGraph.setName(flowComponent.qualifiedName());
Files.createDirectories(targetPath);
writGraphToFile(targetPath.toFile(), flowGraph);
} catch (IOException e) {
log.error("Error while creating parent directory for {}", targetPath, e);
log.error("Skipping individual graph generation for flow {}", flowName);
error("Error while creating parent directory for %s", targetPath, e);
error("Skipping individual graph generation for flow %s", flowName);
return false;
}
return true;
}

boolean writGraphToFile(File outputFilename, MutableGraph graph) {
try {
log.debug("Writing graph at path {}", outputFilename);
debug("Writing graph at path %s", outputFilename);
return GraphvizEngineHelper.generate(graph, Format.PNG, outputFilename);
} catch (IOException e) {
log.error("Error while writing graph at {}", outputFilename, e);
error("Error while writing graph at %s", outputFilename, e);
return false;
}
}
Expand Down Expand Up @@ -216,7 +212,7 @@ MutableNode asSourceNode(MutableNode node) {
MutableNode processComponent(Component component, DrawingContext drawingContext,
Map<String, Component> flowRefs, List<String> mappedFlowKinds,
List<MutableNode> additionalRootNodes) {
log.debug("Processing flow - {}", component.qualifiedName());
debug("Processing flow - %s", component.qualifiedName());
FlowContainer flow = (FlowContainer) component;
MutableNode flowNode = mutNode(flow.qualifiedName()).add(Label.markdown(getNodeLabel(flow)));
if (flow.isaSubFlow()) {
Expand All @@ -235,7 +231,7 @@ MutableNode processComponent(Component component, DrawingContext drawingContext,
k -> targetFlowByName(muleComponent.getName(), drawingContext.getComponents()));
if (refComponent != null) {
if (refComponent.equals(flow)) {
log.warn("Detected a possible self loop in {} {}. Skipping flow-ref processing.",
warn("Detected a possible self loop in %s %s. Skipping flow-ref processing.",
refComponent.getType(), refComponent.getName());
flowNode.addLink(flowNode);
mappedFlowKinds.add(name);
Expand All @@ -261,7 +257,7 @@ MutableNode processComponent(Component component, DrawingContext drawingContext,
// 1. Create a new apikit node for this component
// 2. Find all flows with name ending with ":{apikiConfigName}"
// 3. Link those flows with apiKit flow.
log.debug("Processing apikit component - {}", component.qualifiedName());
debug("Processing apikit component - %s", component.qualifiedName());
MutableNode apiKitNode =
asApikitNode(muleComponent.getType().concat(muleComponent.getConfigRef().getValue()))
.add(Label.htmlLines("<b>" + muleComponent.getType() + "</b>",
Expand Down
Loading

0 comments on commit d8db401

Please sign in to comment.