List of usage examples for org.apache.commons.net.telnet WindowSizeOptionHandler WindowSizeOptionHandler
public WindowSizeOptionHandler(int nWidth, int nHeight, boolean initlocal, boolean initremote, boolean acceptlocal, boolean acceptremote)
From source file:com.xebialabs.overthere.cifs.telnet.CifsTelnetConnection.java
@Override public OverthereProcess startProcess(final CmdLine cmd) { checkNotNull(cmd, "Cannot execute null command line"); checkArgument(cmd.getArguments().size() > 0, "Cannot execute empty command line"); final String obfuscatedCmd = cmd.toCommandLine(os, true); logger.info("Starting command [{}] on [{}]", obfuscatedCmd, this); try {//from w ww . ja va 2s.c om final TelnetClient tc = new TelnetClient(); tc.setConnectTimeout(connectionTimeoutMillis); tc.addOptionHandler(new WindowSizeOptionHandler(299, 25, true, false, true, false)); logger.info("Connecting to telnet://{}@{}", username, address); tc.connect(address, port); final InputStream stdout = tc.getInputStream(); final OutputStream stdin = tc.getOutputStream(); final PipedInputStream callersStdout = new PipedInputStream(); final PipedOutputStream toCallersStdout = new PipedOutputStream(callersStdout); final ByteArrayOutputStream outputBuf = new ByteArrayOutputStream(); final int[] exitValue = new int[1]; exitValue[0] = -1; final Thread outputReaderThread = new Thread("Telnet output reader") { @Override public void run() { try { receive(stdout, outputBuf, toCallersStdout, "ogin:"); send(stdin, username); receive(stdout, outputBuf, toCallersStdout, "assword:"); send(stdin, password); receive(stdout, outputBuf, toCallersStdout, ">", "ogon failure"); send(stdin, "PROMPT " + DETECTABLE_WINDOWS_PROMPT); // We must wait for the prompt twice; the first time is an echo of the PROMPT command, // the second is the actual prompt receive(stdout, outputBuf, toCallersStdout, DETECTABLE_WINDOWS_PROMPT); receive(stdout, outputBuf, toCallersStdout, DETECTABLE_WINDOWS_PROMPT); if (workingDirectory != null) { send(stdin, "CD /D " + workingDirectory.getPath()); receive(stdout, outputBuf, toCallersStdout, DETECTABLE_WINDOWS_PROMPT); } send(stdin, cmd.toCommandLine(getHostOperatingSystem(), false)); receive(stdout, outputBuf, toCallersStdout, DETECTABLE_WINDOWS_PROMPT); send(stdin, "ECHO \"" + ERRORLEVEL_PREAMBLE + "%errorlevel%" + ERRORLEVEL_POSTAMBLE); receive(stdout, outputBuf, toCallersStdout, ERRORLEVEL_POSTAMBLE); receive(stdout, outputBuf, toCallersStdout, ERRORLEVEL_POSTAMBLE); String outputBufStr = outputBuf.toString(); int preamblePos = outputBufStr.indexOf(ERRORLEVEL_PREAMBLE); int postamblePos = outputBufStr.indexOf(ERRORLEVEL_POSTAMBLE); if (preamblePos >= 0 && postamblePos >= 0) { String errorlevelString = outputBufStr .substring(preamblePos + ERRORLEVEL_PREAMBLE.length(), postamblePos); logger.debug("Errorlevel string found: {}", errorlevelString); try { synchronized (exitValue) { exitValue[0] = Integer.parseInt(errorlevelString); } } catch (NumberFormatException exc) { logger.error("Cannot parse errorlevel in Windows output: " + outputBuf); } } else { logger.error("Cannot find errorlevel in Windows output: " + outputBuf); } } catch (IOException exc) { throw new RuntimeIOException(format("Cannot start command [%s] on [%s]", obfuscatedCmd, CifsTelnetConnection.this), exc); } finally { closeQuietly(toCallersStdout); } } }; outputReaderThread.setDaemon(true); outputReaderThread.start(); return new OverthereProcess() { @Override public synchronized OutputStream getStdin() { return stdin; } @Override public synchronized InputStream getStdout() { return callersStdout; } @Override public synchronized InputStream getStderr() { return new ByteArrayInputStream(new byte[0]); } @Override public synchronized int waitFor() { if (!tc.isConnected()) { return exitValue[0]; } try { try { outputReaderThread.join(); } finally { disconnect(); } return exitValue[0]; } catch (InterruptedException exc) { throw new RuntimeIOException(format("Cannot start command [%s] on [%s]", obfuscatedCmd, CifsTelnetConnection.this), exc); } } @Override public synchronized void destroy() { if (!tc.isConnected()) { return; } disconnect(); } private synchronized void disconnect() { try { tc.disconnect(); logger.info("Disconnected from {}", CifsTelnetConnection.this); closeQuietly(toCallersStdout); } catch (IOException exc) { throw new RuntimeIOException(format("Cannot disconnect from %s", CifsTelnetConnection.this), exc); } } @Override public synchronized int exitValue() { if (tc.isConnected()) { throw new IllegalThreadStateException( format("Process for command [%s] on %s is still running", obfuscatedCmd, CifsTelnetConnection.this)); } synchronized (exitValue) { return exitValue[0]; } } }; } catch (InvalidTelnetOptionException exc) { throw new RuntimeIOException( "Cannot execute command " + cmd + " at telnet://" + username + "@" + address, exc); } catch (IOException exc) { throw new RuntimeIOException( "Cannot execute command " + cmd + " at telnet://" + username + "@" + address, exc); } }
From source file:io.termd.core.telnet.TelnetHandlerTest.java
@Test public void testRejectNAWS() throws Exception { final AtomicReference<Boolean> serverValue = new AtomicReference<>(); WindowSizeOptionHandler optionHandler = new WindowSizeOptionHandler(20, 10, false, false, false, false); testOptionValue(new Supplier<TelnetHandler>() { @Override//from ww w. j a v a 2 s .c o m public TelnetHandler get() { return new TelnetHandler() { @Override protected void onOpen(TelnetConnection conn) { conn.writeDoOption(Option.NAWS); } @Override protected void onNAWS(boolean naws) { serverValue.set(naws); testComplete(); } @Override protected void onSize(int width, int height) { super.onSize(width, height); } }; } }, optionHandler); assertEquals(false, serverValue.get()); assertEquals(false, optionHandler.getAcceptLocal()); }
From source file:com.xebialabs.overthere.telnet.TelnetConnection.java
@Override public OverthereProcess startProcess(final CmdLine cmd) { checkNotNull(cmd, "Cannot execute null command line"); checkArgument(cmd.getArguments().size() > 0, "Cannot execute empty command line"); final String obfuscatedCmd = cmd.toCommandLine(os, true); logger.info("Starting command [{}] on [{}]", obfuscatedCmd, this); try {/*from w ww .j a va 2s. co m*/ final TelnetClient tc = new TelnetClient(); tc.setSocketFactory(mapper.socketFactory()); tc.setConnectTimeout(connectionTimeoutMillis); tc.addOptionHandler(new WindowSizeOptionHandler(299, 25, true, false, true, false)); logger.info("Connecting to telnet://{}@{}", username, address); tc.connect(address, port); tc.setSoTimeout(socketTimeoutMillis); final InputStream stdout = tc.getInputStream(); final OutputStream stdin = tc.getOutputStream(); final PipedInputStream callersStdout = new PipedInputStream(); final PipedOutputStream toCallersStdout = new PipedOutputStream(callersStdout); final ByteArrayOutputStream outputBuf = new ByteArrayOutputStream(); final int[] exitValue = new int[1]; exitValue[0] = -1; final Thread outputReaderThread = new Thread("Telnet output reader") { @Override public void run() { try { receive(stdout, outputBuf, toCallersStdout, "ogin:"); send(stdin, username); receive(stdout, outputBuf, toCallersStdout, "assword:"); send(stdin, password); receive(stdout, outputBuf, toCallersStdout, ">", "ogon failure"); send(stdin, "PROMPT " + DETECTABLE_WINDOWS_PROMPT); // We must wait for the prompt twice; the first time is an echo of the PROMPT command, // the second is the actual prompt receive(stdout, outputBuf, toCallersStdout, DETECTABLE_WINDOWS_PROMPT); receive(stdout, outputBuf, toCallersStdout, DETECTABLE_WINDOWS_PROMPT); if (workingDirectory != null) { send(stdin, "CD /D " + workingDirectory.getPath()); receive(stdout, outputBuf, toCallersStdout, DETECTABLE_WINDOWS_PROMPT); } send(stdin, cmd.toCommandLine(os, false)); receive(stdout, outputBuf, toCallersStdout, DETECTABLE_WINDOWS_PROMPT); send(stdin, "ECHO \"" + ERRORLEVEL_PREAMBLE + "%errorlevel%" + ERRORLEVEL_POSTAMBLE); receive(stdout, outputBuf, toCallersStdout, ERRORLEVEL_POSTAMBLE); receive(stdout, outputBuf, toCallersStdout, ERRORLEVEL_POSTAMBLE); String outputBufStr = outputBuf.toString(); int preamblePos = outputBufStr.indexOf(ERRORLEVEL_PREAMBLE); int postamblePos = outputBufStr.indexOf(ERRORLEVEL_POSTAMBLE); if (preamblePos >= 0 && postamblePos >= 0) { String errorlevelString = outputBufStr .substring(preamblePos + ERRORLEVEL_PREAMBLE.length(), postamblePos); logger.debug("Errorlevel string found: {}", errorlevelString); try { synchronized (exitValue) { exitValue[0] = Integer.parseInt(errorlevelString); } } catch (NumberFormatException exc) { logger.error("Cannot parse errorlevel in Windows output: " + outputBuf); } } else { logger.error("Cannot find errorlevel in Windows output: " + outputBuf); } } catch (IOException exc) { throw new RuntimeIOException( format("Cannot start command [%s] on [%s]", obfuscatedCmd, TelnetConnection.this), exc); } finally { closeQuietly(toCallersStdout); } } }; outputReaderThread.setDaemon(true); outputReaderThread.start(); return new OverthereProcess() { @Override public synchronized OutputStream getStdin() { return stdin; } @Override public synchronized InputStream getStdout() { return callersStdout; } @Override public synchronized InputStream getStderr() { return new ByteArrayInputStream(new byte[0]); } @Override public synchronized int waitFor() { if (!tc.isConnected()) { return exitValue[0]; } try { try { outputReaderThread.join(); } finally { disconnect(); } return exitValue[0]; } catch (InterruptedException exc) { throw new RuntimeIOException( format("Cannot start command [%s] on [%s]", obfuscatedCmd, TelnetConnection.this), exc); } } @Override public synchronized void destroy() { if (!tc.isConnected()) { return; } disconnect(); } private synchronized void disconnect() { try { tc.disconnect(); logger.info("Disconnected from {}", TelnetConnection.this); closeQuietly(toCallersStdout); } catch (IOException exc) { throw new RuntimeIOException(format("Cannot disconnect from %s", TelnetConnection.this), exc); } } @Override public synchronized int exitValue() { if (tc.isConnected()) { throw new IllegalThreadStateException( format("Process for command [%s] on %s is still running", obfuscatedCmd, TelnetConnection.this)); } synchronized (exitValue) { return exitValue[0]; } } }; } catch (InvalidTelnetOptionException exc) { throw new RuntimeIOException( "Cannot execute command " + cmd + " at telnet://" + username + "@" + address, exc); } catch (IOException exc) { throw new RuntimeIOException( "Cannot execute command " + cmd + " at telnet://" + username + "@" + address, exc); } }
From source file:io.termd.core.telnet.TelnetHandlerTest.java
@Test public void testAcceptNAWS() throws Exception { final AtomicReference<Boolean> serverValue = new AtomicReference<>(); final AtomicReference<int[]> size = new AtomicReference<>(); WindowSizeOptionHandler optionHandler = new WindowSizeOptionHandler(20, 10, false, false, true, false); testOptionValue(() -> new TelnetHandler() { @Override/*from www . ja v a 2 s.c o m*/ protected void onOpen(TelnetConnection conn) { conn.writeDoOption(Option.NAWS); } @Override protected void onNAWS(boolean naws) { serverValue.set(naws); } @Override protected void onSize(int width, int height) { size.set(new int[] { width, height }); testComplete(); } }, optionHandler); assertEquals(true, serverValue.get()); assertEquals(true, optionHandler.getAcceptLocal()); assertEquals(2, size.get().length); assertEquals(20, size.get()[0]); assertEquals(10, size.get()[1]); }
From source file:io.vertx.ext.shell.term.TelnetTermServerTest.java
@Test public void testWindowSize(TestContext context) throws Exception { Async async = context.async();//w w w.ja va 2s. c o m startTelnet(context, term -> { context.assertEquals(-1, term.width()); context.assertEquals(-1, term.height()); term.resizehandler(v -> { context.assertEquals(10, term.width()); context.assertEquals(20, term.height()); async.complete(); }); }); client.addOptionHandler(new WindowSizeOptionHandler(10, 20, false, false, true, false)); client.connect("localhost", server.actualPort()); }
From source file:io.vertx.ext.shell.term.TelnetTermServerTest.java
@Test public void testOutBinaryTrue(TestContext context) throws Exception { startTelnet(context, new TelnetTermOptions().setOutBinary(true), term -> { term.write("\u20AC"); });/*ww w. ja v a 2s . c om*/ client.addOptionHandler(new WindowSizeOptionHandler(10, 20, false, false, true, false)); client.connect("localhost", server.actualPort()); InputStream in = client.getInputStream(); context.assertEquals(226, in.read()); context.assertEquals(130, in.read()); context.assertEquals(172, in.read()); }
From source file:io.vertx.ext.shell.term.TelnetTermServerTest.java
@Test public void testOutBinaryFalse(TestContext context) throws Exception { byte[] expected = StandardCharsets.US_ASCII.encode("").array(); startTelnet(context, new TelnetTermOptions().setOutBinary(false), term -> { term.write("\u20AC"); });/*www . ja va 2s .c o m*/ client.addOptionHandler(new WindowSizeOptionHandler(10, 20, false, false, true, false)); client.connect("localhost", server.actualPort()); InputStream in = client.getInputStream(); for (int i = 0; i < expected.length; i++) { context.assertEquals((int) expected[i], in.read()); } }
From source file:org.aesh.terminal.telnet.TelnetTermTest.java
@Test public void testSizeHandler() throws Exception { final CountDownLatch latch1 = new CountDownLatch(1); final CountDownLatch latch2 = new CountDownLatch(1); server.start(() -> {//ww w. j a v a2s. c om final AtomicInteger count = new AtomicInteger(); return new TelnetTtyConnection(false, false, StandardCharsets.UTF_8, conn -> { conn.setSizeHandler(size -> { switch (count.getAndIncrement()) { case 0: assertEquals(20, size.getWidth()); assertEquals(10, size.getHeight()); latch1.countDown(); break; case 1: assertEquals(80, size.getWidth()); assertEquals(24, size.getHeight()); latch2.countDown(); break; case 2: assertEquals(180, size.getWidth()); assertEquals(160, size.getHeight()); testComplete(); break; default: fail("Was not expecting that"); } }); }); }); WindowSizeOptionHandler optionHandler = new WindowSizeOptionHandler(20, 10, false, false, true, false); client.setOptionHandler(optionHandler); client.connect("localhost", 4000); latch1.await(30, TimeUnit.SECONDS); client.writeDirectAndFlush(new byte[] { TelnetConnection.BYTE_IAC, TelnetConnection.BYTE_SB, 31, 0, 80, 0, 24, TelnetConnection.BYTE_IAC, TelnetConnection.BYTE_SE }); latch2.await(30, TimeUnit.SECONDS); client.writeDirectAndFlush(new byte[] { TelnetConnection.BYTE_IAC, TelnetConnection.BYTE_SB, 31, 0, (byte) 180, 0, (byte) 160, TelnetConnection.BYTE_IAC, TelnetConnection.BYTE_SE }); await(); }
From source file:org.aesh.terminal.telnet.tty.TelnetTtyTestBase.java
@Override public void testSize() throws Exception { wsHandler = new WindowSizeOptionHandler(80, 24, false, false, true, true); client.setOptionHandler(wsHandler);// w ww.jav a2 s . c om super.testSize(); }