Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package de.cornelius.may.telnet;
- import de.cornelius.may.Bot;
- import lombok.Getter;
- import org.jetbrains.annotations.NotNull;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.PrintWriter;
- import java.net.Socket;
- import java.util.Objects;
- import java.util.concurrent.*;
- public class Telnet {
- @Getter
- private String host;
- @Getter
- private int port;
- @Getter
- private String confirmationString;
- private boolean connected;
- private Socket socket;
- private PrintWriter out;
- private BufferedReader in;
- public Telnet(String host, int port, String confirmationString) throws IOException {
- this.host = host;
- this.port = port;
- this.confirmationString = confirmationString;
- socket = new Socket(host, port);
- out = new PrintWriter(socket.getOutputStream(), true);
- in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
- connected = true;
- Bot.getLogManager().info("Connected telnet: \n");
- while(in.ready()) {
- String line = in.readLine();
- if(line.equals("")) continue;
- Bot.getLogManager().info(line);
- }
- }
- public synchronized void close() throws IOException {
- if(!connected) throw new IllegalArgumentException("Not connected!");
- connected = false;
- out.close();
- in.close();
- socket.close();
- }
- public synchronized String sendCommand(String command) {
- out.println(command);
- try {
- Future<Object> response = Bot.getPool().submit(getResponse);
- return response.get(1, TimeUnit.MINUTES).toString();
- } catch (InterruptedException | ExecutionException | TimeoutException ex) {
- Bot.getLogManager().error("Error while getting response for command '" + command + "'", ex);
- }
- return null;
- }
- private Callable<Object> getResponse = new Callable<Object>() {
- @NotNull
- public Object call() {
- StringBuilder responseBuilder = new StringBuilder();
- while(true) {
- String line = null;
- try {
- line = in.readLine();
- } catch (IOException ex) {
- Bot.getLogManager().error("Error while reading response line", ex);
- }
- if(Objects.equals(line, "") || Objects.equals(line, "\r\n")) continue;
- responseBuilder.append(line).append("\n");
- if(Objects.equals(line, confirmationString)) break;
- }
- String response = responseBuilder.toString();
- return response.substring(0, (response.length() - 1));
- }
- };
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement