use of com.googlecode.lanterna.terminal.Terminal in project java-docs-samples by GoogleCloudPlatform.
the class ManagerIT method testTerminal.
@Test
public void testTerminal() throws Exception {
// Set up
Screen screen = null;
DefaultTerminalFactory defaultTerminalFactory = new DefaultTerminalFactory();
Terminal terminal = defaultTerminalFactory.createTerminal();
screen = new TerminalScreen(terminal);
Screen finalScreen = screen;
Thread deviceThread = new Thread(() -> {
try {
MqttCommandsDemo.startGui(finalScreen, new TextColor.RGB(255, 255, 255));
} catch (IOException e) {
e.printStackTrace();
}
});
deviceThread.join(3000);
System.out.println(terminal.getTerminalSize().toString());
// Assertions
Assert.assertTrue(terminal.getTerminalSize().toString().contains("x"));
Assert.assertTrue(terminal.getTerminalSize().toString().contains("{"));
Assert.assertTrue(terminal.getTerminalSize().toString().contains("}"));
}
use of com.googlecode.lanterna.terminal.Terminal in project java-docs-samples by GoogleCloudPlatform.
the class MqttCommandsDemo method mqttDeviceDemo.
public static void mqttDeviceDemo(String projectId, String cloudRegion, String registryId, String deviceId, String privateKeyFile, String algorithm, String mqttBridgeHostname, short mqttBridgePort, String messageType, int waitTime) throws NoSuchAlgorithmException, IOException, InvalidKeySpecException, MqttException, InterruptedException {
// Build the connection string for Google's Cloud IoT Core MQTT server. Only SSL
// connections are accepted. For server authentication, the JVM's root certificates
// are used.
final String mqttServerAddress = String.format("ssl://%s:%s", mqttBridgeHostname, mqttBridgePort);
// Create our MQTT client. The mqttClientId is a unique string that identifies this device. For
// Google Cloud IoT Core, it must be in the format below.
final String mqttClientId = String.format("projects/%s/locations/%s/registries/%s/devices/%s", projectId, cloudRegion, registryId, deviceId);
MqttConnectOptions connectOptions = new MqttConnectOptions();
// Note that the Google Cloud IoT Core only supports MQTT 3.1.1, and Paho requires that we
// explictly set this. If you don't set MQTT version, the server will immediately close its
// connection to your device.
connectOptions.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
Properties sslProps = new Properties();
sslProps.setProperty("com.ibm.ssl.protocol", "TLSv1.2");
connectOptions.setSSLProperties(sslProps);
// With Google Cloud IoT Core, the username field is ignored, however it must be set for the
// Paho client library to send the password field. The password field is used to transmit a JWT
// to authorize the device.
connectOptions.setUserName("unused");
DateTime iat = new DateTime();
if (algorithm.equals("RS256")) {
connectOptions.setPassword(createJwtRsa(projectId, privateKeyFile).toCharArray());
} else if (algorithm.equals("ES256")) {
connectOptions.setPassword(createJwtEs(projectId, privateKeyFile).toCharArray());
} else {
throw new IllegalArgumentException("Invalid algorithm " + algorithm + ". Should be one of 'RS256' or 'ES256'.");
}
// [START iot_mqtt_publish]
// Create a client, and connect to the Google MQTT bridge.
MqttClient client = new MqttClient(mqttServerAddress, mqttClientId, new MemoryPersistence());
// Both connect and publish operations may fail. If they do, allow retries but with an
// exponential backoff time period.
long initialConnectIntervalMillis = 500L;
long maxConnectIntervalMillis = 6000L;
long maxConnectRetryTimeElapsedMillis = 900000L;
float intervalMultiplier = 1.5f;
long retryIntervalMs = initialConnectIntervalMillis;
long totalRetryTimeMs = 0;
while (!client.isConnected() && totalRetryTimeMs < maxConnectRetryTimeElapsedMillis) {
try {
client.connect(connectOptions);
} catch (MqttException e) {
int reason = e.getReasonCode();
// If the connection is lost or if the server cannot be connected, allow retries, but with
// exponential backoff.
System.out.println("An error occurred: " + e.getMessage());
if (reason == MqttException.REASON_CODE_CONNECTION_LOST || reason == MqttException.REASON_CODE_SERVER_CONNECT_ERROR) {
System.out.println("Retrying in " + retryIntervalMs / 1000.0 + " seconds.");
Thread.sleep(retryIntervalMs);
totalRetryTimeMs += retryIntervalMs;
retryIntervalMs *= intervalMultiplier;
if (retryIntervalMs > maxConnectIntervalMillis) {
retryIntervalMs = maxConnectIntervalMillis;
}
} else {
throw e;
}
}
}
// Publish to the events or state topic based on the flag.
String subTopic = messageType.equals("event") ? "events" : messageType;
// The MQTT topic that this device will publish telemetry data to. The MQTT topic name is
// required to be in the format below. Note that this is not the same as the device registry's
// Cloud Pub/Sub topic.
String mqttTopic = String.format("/devices/%s/%s", deviceId, subTopic);
DefaultTerminalFactory defaultTerminalFactory = new DefaultTerminalFactory();
Screen screen = null;
Terminal terminal = defaultTerminalFactory.createTerminal();
screen = new TerminalScreen(terminal);
attachCallback(client, deviceId, screen);
// Wait for commands to arrive for about two minutes.
for (int i = 1; i <= waitTime; ++i) {
System.out.print(".");
Thread.sleep(1000);
}
System.out.println("");
// Disconnect the client if still connected, and finish the run.
if (client.isConnected()) {
client.disconnect();
}
System.out.println("Finished loop successfully. Goodbye!");
client.close();
System.exit(0);
// [END iot_mqtt_publish]
}
use of com.googlecode.lanterna.terminal.Terminal in project nzyme by lennartkoopmann.
the class TextGUIHID method initializeGUI.
private void initializeGUI() throws IOException {
Terminal terminal = new DefaultTerminalFactory().setInitialTerminalSize(new TerminalSize(COLS, ROWS)).createTerminal();
Screen screen = new TerminalScreen(terminal);
screen.startScreen();
BasicWindow window = new BasicWindow();
Panel mainPanel = new Panel();
// Top status.
Panel statusPanel = new Panel(new GridLayout(8));
statusPanel.addComponent(labelConnection.withBorder(Borders.singleLine("CONN")));
statusPanel.addComponent(labelSignal.withBorder(Borders.singleLine("SIG")));
statusPanel.addComponent(labelTrackerStatus.withBorder(Borders.singleLine("LINK DVC")));
statusPanel.addComponent(labelWiFiStatus.withBorder(Borders.singleLine("802.11")));
statusPanel.addComponent(labelWiFiChannels.withBorder(Borders.singleLine("CHANNEL")));
statusPanel.addComponent(labelDesignator.withBorder(Borders.singleLine("DSGNTR")));
statusPanel.addComponent(new EmptySpace(new TerminalSize(3, 3)));
statusPanel.addComponent(labelTime.withBorder(Borders.singleLine("CLOCK")));
mainPanel.addComponent(statusPanel);
// Task.
Panel taskPanel = new Panel(new GridLayout(6));
taskPanel.addComponent(labelTask.withBorder(Borders.singleLine("TASK")));
taskPanel.addComponent(labelBandit.withBorder(Borders.singleLine("BANDIT TARGET")));
taskPanel.addComponent(labelTrack.withBorder(Borders.singleLine("TRACK")));
taskPanel.addComponent(labelTrackSignal.withBorder(Borders.singleLine("TRACK SIG")));
taskPanel.addComponent(labelTrackFrames.withBorder(Borders.singleLine("FRAMES")));
taskPanel.addComponent(labelTrackContact.withBorder(Borders.singleLine("LAST CONTACT")));
mainPanel.addComponent(taskPanel);
// Events
Panel eventsPanel = new Panel(new GridLayout(1));
eventsPanel.addComponent(eventsTable.withBorder(Borders.singleLine("EVENTS")));
eventsTable.setCellSelection(false);
eventsTable.setSelectedRow(-1);
eventsTable.setVisibleRows(5);
eventsTable.setSize(new TerminalSize(COLS, 8));
event(nzyme.getNodeID(), "Initialized tracker.");
mainPanel.addComponent(eventsPanel);
window.setComponent(mainPanel);
window.setTheme(SimpleTheme.makeTheme(true, TextColor.ANSI.WHITE, TextColor.ANSI.BLACK, TextColor.ANSI.BLACK, TextColor.ANSI.BLUE, TextColor.ANSI.WHITE, TextColor.ANSI.RED, TextColor.ANSI.RED));
window.setHints(Arrays.asList(Window.Hint.CENTERED, Window.Hint.NO_DECORATIONS));
MultiWindowTextGUI gui = new MultiWindowTextGUI(screen, new DefaultWindowManager(), new EmptySpace(TextColor.ANSI.BLACK));
gui.addWindowAndWait(window);
}
use of com.googlecode.lanterna.terminal.Terminal in project security-lib by ncsa.
the class FullScreenTextGUITest method main.
public static void main(String[] args) throws IOException, InterruptedException {
DefaultTerminalFactory factory = new DefaultTerminalFactory();
Terminal terminal = factory.createTerminal();
// Screen screen = new TestTerminalFactory(args).setInitialTerminalSize(new TerminalSize(80, 25)).createScreen();
Screen screen = new TerminalScreen(terminal);
screen.startScreen();
final AtomicBoolean stop = new AtomicBoolean(false);
MultiWindowTextGUI textGUI = new MultiWindowTextGUI(screen);
textGUI.addListener((textGUI1, key) -> {
if (key.getKeyType() == KeyType.Escape) {
stop.set(true);
return true;
}
return false;
});
try {
textGUI.getBackgroundPane().setComponent(new BIOS());
while (!stop.get()) {
if (!textGUI.getGUIThread().processEventsAndUpdate()) {
Thread.sleep(1);
}
}
} catch (EOFException ignore) {
// Terminal closed Left
} finally {
screen.stopScreen();
}
}
use of com.googlecode.lanterna.terminal.Terminal in project security-lib by ncsa.
the class GUIDemo method mytest.
protected static void mytest() throws IOException {
// Note UnixTerminal is supported BUT will freee the IDE because of
// how it uses standard out. Write everything letting Lanterna decide
// what works then switch when running in xterm.
// Next three are required to start pretty much anything
DefaultTerminalFactory factory = new DefaultTerminalFactory();
// All this to set the background color of the terminal...
TerminalEmulatorPalette myPallette = new TerminalEmulatorPalette(// sets default
Color.WHITE, // sets default Bright
Color.RED, // sets background. This is the only reason for this constructor
Color.BLUE, Color.black, Color.BLACK, Color.red, Color.RED, Color.green, Color.GREEN, Color.yellow, Color.YELLOW, Color.blue, Color.BLUE, Color.magenta, Color.MAGENTA, Color.cyan, Color.CYAN, Color.white, Color.WHITE);
// TerminalEmulatorPalette palette = new TerminalEmulatorPalette()
TerminalEmulatorColorConfiguration colorConfig = TerminalEmulatorColorConfiguration.newInstance(myPallette);
factory.setTerminalEmulatorColorConfiguration(colorConfig);
Terminal terminal = factory.createTerminal();
System.out.println("terminal is " + terminal.getClass().getSimpleName());
Screen screen = new TerminalScreen(terminal);
// sets up a resize listener in case the user changes the size.
/* terminal.addResizeListener((terminal1, newSize) -> {
// Be careful here though, this is likely running on a separate thread. Lanterna is threadsafe in
// a best-effort way so while it shouldn't blow up if you call terminal methods on multiple threads,
// it might have unexpected behavior if you don't do any external synchronization
textGraphics.drawLine(5, 3, newSize.getColumns() - 1, 3, ' ');
textGraphics.putString(5, 3, "Terminal Size: ", SGR.BOLD);
textGraphics.putString(5 + "Terminal Size: ".length(), 3, newSize.toString());
try {
terminal1.flush();
} catch (IOException e) {
// Not much we can do here
throw new RuntimeException(e);
}
});*/
TextGraphics textGraphics = screen.newTextGraphics();
// textGraphics.setForegroundColor(TextColor.ANSI.YELLOW);
screen.startScreen();
// clear out any cruft in object properly.
screen.refresh();
// textGraphics.
// Only one of these should be uncommented at any time since they are separate demos.
// showStuff(textGraphics);
// terminal.flush();
// helloWorld(screen);
// userInput2(terminal, screen, textGraphics);
// testBox(screen);
terminalInput(terminal, screen, textGraphics);
screen.stopScreen();
}
Aggregations