org.bidib.wizard.common.script.common.EchoCommand Maven / Gradle / Ivy
package org.bidib.wizard.common.script.common;
import java.util.Map;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.text.StringSubstitutor;
import org.bidib.wizard.api.context.ApplicationContext;
import org.bidib.wizard.api.service.console.ConsoleService;
import org.bidib.wizard.common.script.AbstractScriptCommand;
import org.bidib.wizard.common.script.DefaultScriptContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class EchoCommand extends AbstractScriptCommand {
private static final Logger LOGGER = LoggerFactory.getLogger(EchoCommand.class);
private static final String REGEX = "([\\\"'])(?:(?=(\\\\?))\\2.)*?\\1";
public static final String KEY = "echo";
public static final String HELP =
CODE_BLOCK_START + KEY + prepareHelpHtml(" ") + DIV_END + prepareHelpHtml(
"\nShow a message in the script console window.\nSupport for placeholder substitution is available with ${...}.\n\nExample:\n")
+ CODE_BLOCK_START + prepareHelpHtml("echo \"Show my MAC address: ${macAddress}\"") + DIV_END;
private String echoText;
// pattern for placeholders
private final Pattern p = Pattern.compile("\\$\\{.+\\}");
public EchoCommand(final ConsoleService consoleService) {
super(consoleService, KEY, HELP);
}
@Override
public void parse(String commandLine) {
try (Scanner scanner = new Scanner(commandLine)) {
if (!getKey().equals(scanner.next())) {
LOGGER.info("Invalid command is scanned, key does not match.");
}
line = commandLine.trim();
echoText = scanner.findInLine(REGEX);
if (echoText == null) {
echoText = scanner.findInLine(".+").trim();
}
else {
// strip the leading and trailing char
echoText = echoText.substring(1, echoText.length() - 1);
}
}
LOGGER.info("Parsed command, echoText: {}", echoText);
}
protected String getEchoText() {
return echoText;
}
@Override
protected void internalExecute(T scripting, ApplicationContext context) {
LOGGER.info("Echo the text: {}", echoText);
Matcher matcher = p.matcher(echoText);
if (matcher.find()) {
LOGGER.info("Detected placeholders in string: {}", echoText);
final Map parameters = context.get(DefaultScriptContext.KEY_PARAMETERS, Map.class);
StringSubstitutor sub = new StringSubstitutor(parameters);
String resolvedString = sub.replace(echoText);
scripting.echo(resolvedString);
}
else {
scripting.echo(echoText);
}
}
}