org.jlot.client.configuration.UserConsole Maven / Gradle / Ivy
package org.jlot.client.configuration;
import java.io.IOException;
import javax.inject.Inject;
import jline.console.ConsoleReader;
import org.springframework.context.support.MessageSourceAccessor;
public class UserConsole implements Console
{
@Inject
private ConsoleReader consoleReader;
@Inject
private MessageSourceAccessor messageSourceAccessor;
@Override
public String readLine ( String promptCode, String... args )
{
try
{
return consoleReader.readLine(getLabel(promptCode, args));
}
catch (IOException e)
{
throw new IllegalStateException(e);
}
}
@Override
public String readPassword ( String promptCode, String... args )
{
try
{
return consoleReader.readLine(getLabel(promptCode, args), new Character('*'));
}
catch (IOException e)
{
throw new IllegalStateException(e);
}
}
@Override
public void prompt ( String promptCode, String... args )
{
try
{
consoleReader.println(getPrompt(promptCode, args));
consoleReader.flush();
}
catch (IOException e)
{
throw new IllegalStateException(e);
}
}
private String getLabel ( String promptCode, String[] args )
{
return getPrompt(promptCode, args) + ": ";
}
private String getPrompt ( String promptCode, Object[] args )
{
String prompt = messageSourceAccessor.getMessage(promptCode, args, "");
if (prompt.equals(""))
{
prompt = String.format(promptCode, args);
}
return prompt;
}
@Override
public void newline ( )
{
try
{
consoleReader.println();
consoleReader.flush();
}
catch (IOException e)
{
throw new IllegalStateException(e);
}
}
@Override
public void sure ( String promptCode, String... args )
{
if (yesOrNo(promptCode, args) == false)
{
prompt("Execution canceled");
System.exit(1);
}
}
@Override
public boolean yesOrNo ( String promptCode, String... args )
{
try
{
consoleReader.println();
String prompt = getPrompt(promptCode, args) + " [y/n]: ";
String answer = consoleReader.readLine(prompt);
return "y".equals(answer);
}
catch (IOException e)
{
throw new IllegalStateException(e);
}
}
}