Example usage for org.apache.commons.net.telnet TelnetClient TelnetClient

List of usage examples for org.apache.commons.net.telnet TelnetClient TelnetClient

Introduction

In this page you can find the example usage for org.apache.commons.net.telnet TelnetClient TelnetClient.

Prototype

public TelnetClient() 

Source Link

Document

Default TelnetClient constructor, sets terminal-type VT100 .

Usage

From source file:org.xerela.net.sim.telnet.TelnetTest.java

/**
 * //from  w  w w.  j av  a2 s  .c  om
 * @throws Exception
 */
public void testTelnet() throws Exception {
    /*     Start:
     *   +------------+
     * ,-! Send Input !
     * ! +------------+
     * !     | 
     * ! +------------+
     * ! ! Read Input !------. no
     * ! +------------+       \
     * !yes   |                |
     * ! +------------+ no +------------+ yes +------+
     * `-! IsCorrect? !----! IsTooLong? !-----! FAIL !
     *   +------------+    +------------+     +------+
     * 
     */
    IpAddress local = IpAddress.getIpAddress(Util.getLocalHost(), null);

    TelnetClient client = new TelnetClient();
    client.connect(local.getRealAddress());

    RecordingLoader recordingLoader = RecordingLoader.getInstance();
    Configuration config = ConfigurationService.getInstance()
            .findConfigurationFile(ConfigurationService.DEFAULT_CONFIG);

    WorkingConfig wc = config.getDefaultOperationWorkingConfig();

    // create the operation manually first so that we can easily get the records
    RecordingOperation operation = (RecordingOperation) recordingLoader.createOperation(wc, local, local);
    Interaction[] interactions = operation.getInteractions();
    operation.tearDown();

    BufferedInputStream in = new BufferedInputStream(client.getInputStream());
    PrintStream out = new PrintStream(client.getOutputStream(), true);

    byte[] bbuf = new byte[2048];

    CharSequenceBuffer cbuf = new CharSequenceBuffer();
    for (int i = 0; i < interactions.length; i++) {
        Interaction currInteraction = interactions[i];

        String proto = currInteraction.getCliProtocol();
        if (!proto.equals("Telnet")) {
            /*
             * Because the recording might have other protocols we should stop when we encounter one.
             * The recording may not behave properly if we continue as we are.
             * If we got through at least 10 interactions then this test is probably still valid.
             */
            assertTrue(
                    "At least 10 telnet interction should have been handled.  Maybe this test should be run with another recording.",
                    i > 10);
            System.err.println(
                    "Continueing could disrupt the validity of this test.  This test will only support Telnet operations.");
            break;
        }

        // The timeout will be four times the expected time or 4 seconds, whichever is longer.
        Long interactionTime = currInteraction.getEndTime() - currInteraction.getStartTime();
        long time = Math.max((long) (interactionTime * wc.getRateMultiplier()) * 4, 4000);
        long start = System.currentTimeMillis();

        CharSequence input = currInteraction.getCliCommand();
        CharSequence response = currInteraction.getCliResponse();
        if (!input.equals("No input sent") && !input.equals("")) {
            out.println(input);
        }

        cbuf.reset();
        while (true) {
            int len = 0;
            if (in.available() <= 0) {
                try {
                    Thread.sleep(250);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (in.available() <= 0) {
                    if (System.currentTimeMillis() - start > time) {
                        // isTooLong
                        fail("Timeout reached waiting for response for interaction '"
                                + currInteraction.getCliCommand() + "'");
                    }
                    continue;
                }
            }
            len = in.read(bbuf);
            cbuf.write(bbuf, 0, len);

            // isCorrect?
            if (compare(cbuf, response)) {
                break;
            } else if (System.currentTimeMillis() - start > time) {
                // isTooLong
                fail("Timeout reached waiting for response for interaction '" + currInteraction.getCliCommand()
                        + "'");
            }
        }
    }
}

From source file:zhanglw.dubbo.client.service.TelnetClientExample.java

/***
 * Main for the TelnetClientExample./* ww  w .  j a  va 2 s  . c om*/
 * @param args input params
 * @throws Exception on error
 ***/
public static void main(String[] args) throws Exception {
    FileOutputStream fout = null;

    if (args.length < 1) {
        System.err.println("Usage: TelnetClientExample <remote-ip> [<remote-port>]");
        System.exit(1);
    }

    String remoteip = args[0];

    int remoteport;

    if (args.length > 1) {
        remoteport = (new Integer(args[1])).intValue();
    } else {
        remoteport = 23;
    }

    try {
        fout = new FileOutputStream("spy.log", true);
    } catch (IOException e) {
        System.err.println("Exception while opening the spy file: " + e.getMessage());
    }

    tc = new TelnetClient();

    TerminalTypeOptionHandler ttopt = new TerminalTypeOptionHandler("VT100", false, false, true, false);
    EchoOptionHandler echoopt = new EchoOptionHandler(true, false, true, false);
    SuppressGAOptionHandler gaopt = new SuppressGAOptionHandler(true, true, true, true);

    try {
        tc.addOptionHandler(ttopt);
        tc.addOptionHandler(echoopt);
        tc.addOptionHandler(gaopt);
    } catch (InvalidTelnetOptionException e) {
        System.err.println("Error registering option handlers: " + e.getMessage());
    }

    while (true) {
        boolean end_loop = false;
        try {
            tc.connect(remoteip, remoteport);

            Thread reader = new Thread(new TelnetClientExample());
            tc.registerNotifHandler(new TelnetClientExample());
            System.out.println("TelnetClientExample");
            System.out.println("Type AYT to send an AYT telnet command");
            System.out.println("Type OPT to print a report of status of options (0-24)");
            System.out.println("Type REGISTER to register a new SimpleOptionHandler");
            System.out.println("Type UNREGISTER to unregister an OptionHandler");
            System.out.println("Type SPY to register the spy (connect to port 3333 to spy)");
            System.out.println("Type UNSPY to stop spying the connection");
            System.out.println("Type ^[A-Z] to send the control character; use ^^ to send ^");

            reader.start();
            OutputStream outstr = tc.getOutputStream();

            byte[] buff = new byte[1024];
            int ret_read = 0;

            do {
                try {
                    ret_read = System.in.read(buff);
                    if (ret_read > 0) {
                        final String line = new String(buff, 0, ret_read,
                                java.nio.charset.Charset.forName("UTF-8")); // deliberate use of default charset
                        if (line.startsWith("AYT")) {
                            try {
                                System.out.println("Sending AYT");

                                System.out.println("AYT response:" + tc.sendAYT(5000));
                            } catch (IOException e) {
                                System.err.println("Exception waiting AYT response: " + e.getMessage());
                            }
                        } else if (line.startsWith("OPT")) {
                            System.out.println("Status of options:");
                            for (int ii = 0; ii < 25; ii++) {
                                System.out.println("Local Option " + ii + ":" + tc.getLocalOptionState(ii)
                                        + " Remote Option " + ii + ":" + tc.getRemoteOptionState(ii));
                            }
                        } else if (line.startsWith("REGISTER")) {
                            StringTokenizer st = new StringTokenizer(new String(buff));
                            try {
                                st.nextToken();
                                int opcode = Integer.parseInt(st.nextToken());
                                boolean initlocal = Boolean.parseBoolean(st.nextToken());
                                boolean initremote = Boolean.parseBoolean(st.nextToken());
                                boolean acceptlocal = Boolean.parseBoolean(st.nextToken());
                                boolean acceptremote = Boolean.parseBoolean(st.nextToken());
                                SimpleOptionHandler opthand = new SimpleOptionHandler(opcode, initlocal,
                                        initremote, acceptlocal, acceptremote);
                                tc.addOptionHandler(opthand);
                            } catch (Exception e) {
                                if (e instanceof InvalidTelnetOptionException) {
                                    System.err.println("Error registering option: " + e.getMessage());
                                } else {
                                    System.err.println("Invalid REGISTER command.");
                                    System.err.println(
                                            "Use REGISTER optcode initlocal initremote acceptlocal acceptremote");
                                    System.err.println("(optcode is an integer.)");
                                    System.err.println(
                                            "(initlocal, initremote, acceptlocal, acceptremote are boolean)");
                                }
                            }
                        } else if (line.startsWith("UNREGISTER")) {
                            StringTokenizer st = new StringTokenizer(new String(buff));
                            try {
                                st.nextToken();
                                int opcode = (new Integer(st.nextToken())).intValue();
                                tc.deleteOptionHandler(opcode);
                            } catch (Exception e) {
                                if (e instanceof InvalidTelnetOptionException) {
                                    System.err.println("Error unregistering option: " + e.getMessage());
                                } else {
                                    System.err.println("Invalid UNREGISTER command.");
                                    System.err.println("Use UNREGISTER optcode");
                                    System.err.println("(optcode is an integer)");
                                }
                            }
                        } else if (line.startsWith("SPY")) {
                            tc.registerSpyStream(fout);
                        } else if (line.startsWith("UNSPY")) {
                            tc.stopSpyStream();
                        } else if (line.matches("^\\^[A-Z^]\\r?\\n?$")) {
                            byte toSend = buff[1];
                            if (toSend == '^') {
                                outstr.write(toSend);
                            } else {
                                outstr.write(toSend - 'A' + 1);
                            }
                            outstr.flush();
                        } else {
                            try {
                                outstr.write(buff, 0, ret_read);
                                outstr.flush();
                            } catch (IOException e) {
                                end_loop = true;
                            }
                        }
                    }
                } catch (IOException e) {
                    System.err.println("Exception while reading keyboard:" + e.getMessage());
                    end_loop = true;
                }
            } while ((ret_read > 0) && (end_loop == false));

            try {
                tc.disconnect();
            } catch (IOException e) {
                System.err.println("Exception while connecting:" + e.getMessage());
            }
        } catch (IOException e) {
            System.err.println("Exception while connecting:" + e.getMessage());
            System.exit(1);
        }
    }
}

From source file:zhuravlik.textproto.client.TextClient.java

public TextClient() {
    tc = new TelnetClient();
    tc.registerNotifHandler(new EmptyNotifyHandler());
}

From source file:zhuravlik.textproto.client.TextClient.java

public TextClient(TelnetNotificationHandler handler) {
    tc = new TelnetClient();
    tc.registerNotifHandler(handler);
}