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

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

Introduction

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

Prototype

public InputStream getInputStream() 

Source Link

Document

Returns the telnet connection input stream.

Usage

From source file:examples.weatherTelnet.java

public final static void main(String[] args) {
    TelnetClient telnet;

    telnet = new TelnetClient();

    try {/* w ww .  j a v a  2  s.  co  m*/
        telnet.connect("rainmaker.wunderground.com", 3000);
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
    }

    IOUtil.readWrite(telnet.getInputStream(), telnet.getOutputStream(), System.in, System.out);

    try {
        telnet.disconnect();
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
    }

    System.exit(0);
}

From source file:expect4j.ExpectUtils.java

/**
 * TODO Simulate "Could not open connection to the host, on port...."
 * TODO Simulate "Connection refused"/*w  w  w .j  av  a 2  s .  c o  m*/
 */
public static Expect4j telnet(String hostname, int port) throws Exception {
    // This library has trouble with EOF
    final TelnetClient client = new TelnetClient();

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

    client.connect(hostname, port);
    InputStream is = new FromNetASCIIInputStream(client.getInputStream()); // null until client connected
    OutputStream os = new ToNetASCIIOutputStream(client.getOutputStream());

    StreamPair pair = new StreamPair(is, os) {
        public void close() {
            //super.close();
            try {
                if (client != null)
                    client.disconnect();
            } catch (IOException ioe) {

            }
        }
    };

    /*
    URL url=new URL("telnet", hostname, port, "",  new thor.net.URLStreamHandler());
    final URLConnection urlConnection=url.openConnection();
    urlConnection.connect();
    if (urlConnection instanceof TelnetURLConnection) {
    ((TelnetURLConnection)urlConnection).setTelnetTerminalHandler(new SimpleTelnetTerminalHandler());
    }
    OutputStream os=urlConnection.getOutputStream();
    InputStream is=urlConnection.getInputStream();
             
    StreamPair pair = new StreamPair(is, os) {
    public void close() {
        try { ((TelnetURLConnection)urlConnection).disconnect(); }catch(Exception e) { }
    }
    };
     */
    Expect4j expect4j = new Expect4j(pair);

    return expect4j;
}

From source file:eu.europa.ec.fisheries.uvms.plugins.inmarsat.twostage.Connect.java

public String connect(PollType poll, String path, String url, String port, String user, String psw, String dnid)
        throws TelnetException {

    String response = null;//from w w w  .  j  av a  2 s.  co  m
    try {
        TelnetClient telnet = new TelnetClient();

        telnet.connect(url, Integer.parseInt(port));
        BufferedInputStream input = new BufferedInputStream(telnet.getInputStream());
        PrintStream output = new PrintStream(telnet.getOutputStream());

        readUntil("name:", input, null, url, port);
        write(user, output);
        readUntil("word:", input, null, url, port);
        sendPsw(output, psw);
        readUntil(">", input, null, url, port);

        response = issueCommand(poll, output, input, dnid, path, url, port);

        if (telnet.isConnected()) {
            telnet.disconnect();
        }
    } catch (IOException ex) {
        LOG.error("Error when communicating with Telnet", ex);
    } catch (NullPointerException ex) {
        throw new TelnetException(ex);
    }
    return response;
}

From source file:TelnetTest.java

public void testFTP_Telnet_Remote_Execution_003() throws IOException {
    os.write("testexecute\r\n".getBytes());
    os.flush();//  w  w  w .  j  a va2  s  .c o  m

    //this shell will lock, open another one and kill TEF

    TelnetClient tc = new TelnetClient();
    tc.connect(telnetClient.getRemoteAddress());

    InputStream is2 = tc.getInputStream();
    OutputStream os2 = tc.getOutputStream();

    readUntil(is2, prompt);

    os2.write("ps | grep TestExecute\r\n".getBytes());
    os2.flush();

    String s = readUntil(is2, prompt);

    Pattern p = Pattern.compile(".*\\D+(\\d+)\\s[\\s:\\d]+TestExecute Script Engine.*",
            Pattern.DOTALL | Pattern.CASE_INSENSITIVE); //Pattern.DOTALL => '.' includes end of line
    Matcher m = p.matcher(s);

    assertTrue(m.matches());

    String s1 = m.group(1);

    int pid = Integer.parseInt(s1);

    os2.write(("kill " + pid + "\r\n").getBytes());
    os2.flush();
    readUntil(is2, prompt);
    os2.write("bye\r\n".getBytes());
    os2.flush();

    //we should be able now to close the other shell

    readUntil(is, prompt);

}

From source file:li.klass.fhem.fhem.TelnetConnection.java

public RequestResult<String> executeCommand(String command, Context context) {
    LOG.info("executeTask command {}", command);

    final TelnetClient telnetClient = new TelnetClient();
    telnetClient.setConnectTimeout(getConnectionTimeoutMilliSeconds(context));

    BufferedOutputStream bufferedOutputStream = null;
    PrintStream printStream = null;

    String errorHost = serverSpec.getIp() + ":" + serverSpec.getPort();
    try {//from   www. jav a2  s  .  c om
        telnetClient.connect(serverSpec.getIp(), serverSpec.getPort());

        OutputStream outputStream = telnetClient.getOutputStream();
        InputStream inputStream = telnetClient.getInputStream();

        bufferedOutputStream = new BufferedOutputStream(outputStream);
        printStream = new PrintStream(outputStream);

        boolean passwordSent = false;
        String passwordRead = readUntil(inputStream, PASSWORD_PROMPT);
        if (passwordRead != null && passwordRead.contains(PASSWORD_PROMPT)) {
            LOG.info("sending password");
            writeCommand(printStream, serverSpec.getPassword());
            passwordSent = true;
        }

        writeCommand(printStream, "\n\n");

        if (!waitForFilledStream(inputStream, 5000)) {
            return new RequestResult<>(RequestResultError.HOST_CONNECTION_ERROR);
        }

        // to discard
        String toDiscard = read(inputStream);
        LOG.debug("discarding {}", toDiscard);

        writeCommand(printStream, command);

        // If we send an xmllist, we are done when finding the closing FHZINFO tag.
        // If another command is used, the tag ending delimiter is obsolete, not found and
        // therefore not used. We just read until the stream ends.
        String result;
        if (command.equals("xmllist")) {
            result = readUntil(inputStream, "</FHZINFO>");
        } else {
            result = read(inputStream);
        }

        if (result == null && passwordSent) {
            return new RequestResult<>(RequestResultError.AUTHENTICATION_ERROR);
        } else if (result == null) {
            return new RequestResult<>(RequestResultError.INVALID_CONTENT);
        }

        telnetClient.disconnect();

        int startPos = result.indexOf(", try help");
        if (startPos != -1) {
            result = result.substring(startPos + ", try help".length());
        }

        startPos = result.indexOf("<");
        if (startPos != -1) {
            result = result.substring(startPos);
        }

        result = result.replaceAll("Bye...", "").replaceAll("fhem>", "");
        result = new String(result.getBytes("UTF8"));
        LOG.debug("result is {}", result);

        return new RequestResult<>(result);

    } catch (SocketTimeoutException e) {
        LOG.error("timeout", e);
        setErrorInErrorHolderFor(e, errorHost, command);
        return new RequestResult<>(RequestResultError.CONNECTION_TIMEOUT);
    } catch (UnsupportedEncodingException e) {
        // this may never happen, as UTF8 is known ...
        setErrorInErrorHolderFor(e, errorHost, command);
        throw new IllegalStateException("unsupported encoding", e);
    } catch (SocketException e) {
        // We handle host connection errors directly after connecting to the server by waiting
        // for some token for some seconds. Afterwards, the only possibility for an error
        // is that the FHEM server ends the connection after receiving an invalid password.
        LOG.error("SocketException", e);
        setErrorInErrorHolderFor(e, errorHost, command);
        return new RequestResult<>(RequestResultError.AUTHENTICATION_ERROR);
    } catch (IOException e) {
        LOG.error("IOException", e);
        setErrorInErrorHolderFor(e, errorHost, command);
        return new RequestResult<>(RequestResultError.HOST_CONNECTION_ERROR);
    } finally {
        CloseableUtil.close(printStream, bufferedOutputStream);
    }
}

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  w  w .j  a v a 2  s  .  c  o m
        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: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 w  w . ja v  a2 s . c  o  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:it.infn.ct.jsaga.adaptor.rocci.job.rOCCIJobControlAdaptor.java

@Override
public String submit(String jobDesc, boolean checkMatch, String uniqId)
        throws PermissionDeniedException, TimeoutException, NoSuccessException, BadResource {
    String resourceID = "";
    String publicIP = "";
    //List<String> results = new ArrayList();
    List<String> results = new ArrayList<String>();

    if (action.equals("create")) {

        log.info("Creating a new OCCI computeID. Please wait! ");

        if (attributes_title.trim().length() > 0)
            log.info("VM Title     = " + attributes_title);

        if (mixin_os_tpl.trim().length() > 0)
            log.info("OS           = " + mixin_os_tpl);

        if (mixin_resource_tpl.trim().length() > 0)
            log.info("Flavour      = " + mixin_resource_tpl);

        String Execute = prefix + "occi --endpoint " + Endpoint + " --action " + "create" + " --resource "
                + resource + " --attribute occi.core.title=" + attributes_title + " --mixin os_tpl#"
                + mixin_os_tpl + " --mixin resource_tpl#" + mixin_resource_tpl + " --auth " + auth
                + " --user-cred " + user_cred + " --voms --ca-path " + ca_path;

        log.info("");
        log.info(Execute);/*from  w  w  w  .  ja  va 2s. c  o  m*/

        try {
            results = run_OCCI("create", Execute);
            if (results.isEmpty())
                throw new NoSuccessException("Some problems occurred while executing the action create. "
                        + "Please check your settings.");

        } catch (Exception ex) {
            log.error(ex);
        }

        // Getting info about the VM
        if (results.size() > 0) {
            resourceID = results.get(0);

            int k = 0;
            boolean check = false;

            try {
                while (!check) {
                    log.info("");
                    log.info("See below the details of the VM ");
                    log.info("[ " + resourceID + " ]");
                    log.info("");

                    Execute = prefix + "occi --endpoint " + Endpoint + " --action " + "describe"
                            + " --resource " + resource + " --resource " + resourceID + " --auth " + auth
                            + " --user-cred " + user_cred + " --voms --ca-path " + ca_path
                            + " --output-format json_extended_pretty";

                    log.info(Execute);

                    results = run_OCCI("describe", Execute);

                    publicIP = getIP(results);
                    if (!isNullOrEmpty(publicIP))
                        check = true;
                    else
                        check = true;
                } // end while
            } catch (Exception ex) {
                log.error(ex);
            }

            sshControlAdaptor.setSecurityCredential(credential.getSSHCredential());
            log.info("");
            log.info("Starting VM [ " + publicIP + " ] in progress...");

            Date date = new Date();
            SimpleDateFormat ft = new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz");

            log.info("");
            log.info("Waiting the remote VM finishes the boot! Sleeping for a while... ");
            log.info(ft.format(date));

            byte[] buff = new byte[1024];
            int ret_read = 0;
            boolean flag = true;
            int MAX = 0;

            TelnetClient tc = null;

            while ((flag) && (MAX < MAX_CONNECTIONS)) {
                try {
                    tc = new TelnetClient();
                    tc.connect(publicIP, 22);
                    InputStream instr = tc.getInputStream();

                    ret_read = instr.read(buff);
                    if (ret_read > 0) {
                        log.info("[ SUCCESS ] ");
                        tc.disconnect();
                        flag = false;
                    }
                } catch (IOException e) {

                    try {
                        Thread.sleep(60000);
                    } catch (InterruptedException ex) {
                    }

                    MAX++;
                }
            }

            date = new Date();
            log.info(ft.format(date));
        }

        rOCCIJobMonitorAdaptor.setSSHHost(publicIP);

        try {
            sshControlAdaptor.connect(null, publicIP, 22, null, new HashMap());
        } catch (NotImplementedException ex) {
            throw new NoSuccessException(ex);
        } catch (AuthenticationFailedException ex) {
            throw new PermissionDeniedException(ex);
        } catch (AuthorizationFailedException ex) {
            throw new PermissionDeniedException(ex);
        } catch (BadParameterException ex) {
            throw new NoSuccessException(ex);
        }

        return sshControlAdaptor.submit(jobDesc, checkMatch, uniqId) + "@" + publicIP + "#" + resourceID;
    } // end creating

    else
        return null;
}

From source file:it.infn.ct.jsaga.adaptor.jocci.job.jOCCIJobControlAdaptor.java

@Override
public String submit(String jobDesc, boolean checkMatch, String uniqId)
        throws PermissionDeniedException, TimeoutException, NoSuccessException, BadResource {
    String result = "";
    //String networkInterfaceLocation = "";
    //String networkInterfaceLocation_stripped = "";
    //Resource vm_resource = null;
    String publicIP = "";

    if (action.equals("create")) {
        try {/*from   w  ww  .jav a  2 s . co m*/
            log.info("Creating a new resource using jOCCI-api. Please wait!");

            if (attributes_title.trim().length() > 0)
                log.info("VM Title     = " + attributes_title);

            if (mixin_os_tpl.trim().length() > 0)
                log.info("OS           = " + mixin_os_tpl);

            if (mixin_resource_tpl.trim().length() > 0)
                log.info("Flavour      = " + mixin_resource_tpl);

            log.info("");
            if (context_publickey.equals("true")) {
                log.info("EGI FedCloud Contextualisation options:");

                log.info("org.openstack.credentials.publickey.data = "
                        + getPublicKey(credential.getSSHCredential().getPublicKeyFile().getPath()));

                log.info("org.openstack.credentials.publickey.name = " + context_publickey_name);
            } else
                log.info("No contextualization set for the resource.");

            HTTPAuthentication authentication = new VOMSAuthentication(user_cred);

            authentication.setCAPath(ca_path);
            /*Client client = new HTTPClient(URI.create("https://"
                + OCCI_ENDPOINT_HOST + ":"
                + OCCI_ENDPOINT_PORT),
                authentication, MediaType.TEXT_PLAIN, false);*/

            Client client = new HTTPClient(URI.create(protocol + OCCI_ENDPOINT_HOST + ":" + OCCI_ENDPOINT_PORT),
                    authentication, MediaType.TEXT_PLAIN, false);

            //connect client
            client.connect();

            Model model = client.getModel();
            EntityBuilder eb = new EntityBuilder(model);
            Date date = new Date();

            log.info("");
            log.info("[ TEMPLATES ]");
            log.info("- Available os templates mixins ...");
            List<Mixin> mixins = model.findRelatedMixins("os_tpl");

            if (!mixins.isEmpty()) {
                for (Mixin entry : mixins)
                    log.info(entry);

                // 1.) Create a new compute resource
                log.info("");
                log.info("[ CREATE ]");
                Resource compute = eb.getResource("compute");
                Mixin mixin = model.findMixin(mixin_os_tpl);
                compute.addMixin(mixin);
                compute.addMixin(model.findMixin(mixin_os_tpl, "os_tpl"));
                compute.addMixin(model.findMixin(mixin_resource_tpl, "resource_tpl"));
                if (context_publickey.equals("true")) {
                    // Add SSH public key 
                    compute.addMixin(model.findMixin(
                            URI.create("http://schemas.openstack.org/instance/credentials#public_key")));
                    compute.addAttribute("org.openstack.credentials.publickey.name", context_publickey_name);

                    compute.addAttribute("org.openstack.credentials.publickey.data",
                            getPublicKey(credential.getSSHCredential().getPublicKeyFile().getPath()));
                }

                compute.setTitle(attributes_title);
                log.info(mixin.toText());

                log.info("");
                // Creating a new VM resource
                URI location = client.create(compute);

                // Getting the list of available running resources
                List<URI> list = client.list();
                URI uri_location = list.get(0);
                // Listing all the active resources
                //URI uri_location = null;
                log.info("[ LIST ]");
                log.info("- Retieve the list of VMs running on the cloud site");

                for (URI uri : list) {
                    if (uri.toString().contains("compute")) //{
                        log.info("~ " + uri);
                    //uri_location = uri;
                    //}
                }

                log.info("");
                log.info("================= [ R E P O R T ] =================");

                // 3.) Describe resource
                log.info("");
                log.info("[ DESCRIPTION ]");
                if (location != null) {
                    log.info("- Getting VM settings for the resource");
                    log.info(uri_location);
                } else
                    log.error("Some errors occurred during the creation of a new resource.");

                List<Entity> entities = client.describe(uri_location);
                Resource resource = (Resource) entities.get(0);
                vm_resource = resource;
                log.info(entities.get(0).toText());

                SimpleDateFormat ft = new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz");

                log.info("");
                log.info("Waiting the remote VM finishes the boot!");
                log.info(ft.format(date));

                log.info("");
                log.info("Waiting the status of the following resource becomes ACTIVE");
                log.info(uri_location);
                log.info("This operation may take few minutes to complete. Please wait!");
                log.info("");

                try {
                    Thread.sleep(60000);
                } catch (InterruptedException ex) {
                    java.util.logging.Logger.getLogger(jOCCIJobControlAdaptor.class.getName()).log(Level.SEVERE,
                            null, ex);
                }

                while (!entities.get(0).getValue(Compute.STATE_ATTRIBUTE_NAME).equals("active")) {
                    log.info("[ STATUS ] = " + entities.get(0).getValue(Compute.STATE_ATTRIBUTE_NAME));

                    entities = client.describe(uri_location);

                    if (entities.get(0).getValue(Compute.STATE_ATTRIBUTE_NAME).equals("active")) {
                        log.info("[ STATUS ] = " + entities.get(0).getValue(Compute.STATE_ATTRIBUTE_NAME));

                        try {
                            Thread.sleep(30000);
                        } catch (InterruptedException ex) {
                            java.util.logging.Logger.getLogger(jOCCIJobControlAdaptor.class.getName())
                                    .log(Level.SEVERE, null, ex);
                        }

                        // Getting IP address and NetworkLocation 
                        // of the resource
                        String IP = getNetworkLocation(entities)[0];

                        log.info("");
                        log.info("The compute resource is now active!");
                        log.info("URI = " + uri_location);
                        log.info("IP  = " + IP);
                        log.info("");
                        log.info("Check whether the compute resource has a public IP or not ");

                        if (checkIP(IP) != null) {
                            log.info("The compute resource has a *public* IP [ " + IP + " ]");
                            publicIP = IP;
                        } else {
                            log.info("The compute resource has a *private* IP [ " + IP + " ]");

                            // Find a network resource that provides public IPs 
                            String public_network = "";
                            List<URI> uris = client.list("network");
                            log.info("Listing available networks for the given resource");
                            if (!uris.isEmpty()) {
                                // Listing networks
                                for (URI uri : uris) {
                                    //if ((uri.toString()).contains("public"))
                                    if ((uri.toString()).contains(OCCI_PUBLIC_NETWORK_ID))
                                        public_network = uri.toString();

                                    log.info("NetworkID = " + uri.toString());
                                }
                            }

                            try {
                                Thread.sleep(5000);
                            } catch (InterruptedException ex) {
                                java.util.logging.Logger.getLogger(jOCCIJobControlAdaptor.class.getName())
                                        .log(Level.SEVERE, null, ex);
                            }

                            if (public_network != null && !public_network.isEmpty()) {
                                log.info("");
                                log.info("Public Network = " + public_network);
                                log.info("Unlink the network interface that doesn't have public IPs");
                                log.info("NetworkID = " + getNetworkLocation(entities)[1]);
                                client.delete(URI.create((getNetworkLocation(entities)[1])));

                                IPNetworkInterface ipni = eb.getIPNetworkInterface();
                                ipni.setSource(vm_resource);
                                ipni.setTarget(public_network);
                                location = client.create(ipni);

                                // Sleeping for a while
                                try {
                                    Thread.sleep(5000);
                                } catch (InterruptedException ex) {
                                    ex.printStackTrace(System.out);
                                }

                                log.info("");
                                log.info("[ DESCRIPTION ]");
                                entities = client.describe(uri_location);
                                log.info(entities.get(0).toText());

                                String tmp = "";
                                log.info("");
                                log.info("- Get the available IPs for the given VM");
                                for (Entity entity : entities) {
                                    resource = (Resource) entity;
                                    Set<Link> links = resource.getLinks(NetworkInterface.TERM_DEFAULT);

                                    for (Link link : links) {
                                        tmp = link.getValue(IPNetworkInterface.ADDRESS_ATTRIBUTE_NAME);
                                        log.info("IP = " + tmp);
                                        if (checkIP(tmp) != null)
                                            publicIP = tmp;
                                    }
                                } // end-for
                            } // end-if
                        } // end-else

                        log.info("Public IP address = " + publicIP);
                        log.info("Checking for connectivity. Please wait! ");

                        byte[] buff = new byte[1024];
                        int ret_read = 0;
                        boolean flag = true;
                        int MAX = 0;
                        TelnetClient tc = null;

                        while ((flag) && (MAX < MAX_CONNECTIONS)) {
                            try {
                                tc = new TelnetClient();
                                tc.connect(publicIP, 22);
                                InputStream instr = tc.getInputStream();

                                ret_read = instr.read(buff);
                                if (ret_read > 0) {
                                    log.info("SSH daemon has started [ OK ] ");
                                    tc.disconnect();
                                    flag = false;
                                }
                            } catch (IOException e) {
                                log.info("The destination host is unreachable. Sleeping for a while... ");
                                try {
                                    Thread.sleep(60000);
                                } catch (InterruptedException ex) {
                                    java.util.logging.Logger.getLogger(jOCCIJobControlAdaptor.class.getName())
                                            .log(Level.SEVERE, null, ex);
                                }

                                MAX++;
                            }
                        } // end-while

                        date = new Date();
                        log.info(ft.format(date));

                        jOCCIJobMonitorAdaptor.setSSHHost(publicIP);

                        try {
                            sshControlAdaptor.connect(null, publicIP, 22, null, new HashMap());
                        } catch (NotImplementedException ex) {
                            throw new NoSuccessException(ex);
                        } catch (AuthenticationFailedException ex) {
                            throw new PermissionDeniedException(ex);
                        } catch (AuthorizationFailedException ex) {
                            throw new PermissionDeniedException(ex);
                        } catch (BadParameterException ex) {
                            throw new NoSuccessException(ex);
                        }

                        result = sshControlAdaptor.submit(jobDesc, checkMatch, uniqId) + "@" + publicIP + "#"
                                + uri_location;

                        break;
                    } else {
                        try {
                            // Sleeping for a while ...
                            Thread.sleep(5000);
                        } catch (InterruptedException ex) {
                            java.util.logging.Logger.getLogger(jOCCIJobControlAdaptor.class.getName())
                                    .log(Level.SEVERE, null, ex);
                        }
                    } //end-else
                } //end-while

            } else
                log.error("No OS template mixins available!");

        } catch (RenderingException ex) {
            java.util.logging.Logger.getLogger(jOCCIJobControlAdaptor.class.getName()).log(Level.SEVERE, null,
                    ex);
        } catch (InvalidAttributeValueException ex) {
            java.util.logging.Logger.getLogger(jOCCIJobControlAdaptor.class.getName()).log(Level.SEVERE, null,
                    ex);
        } catch (EntityBuildingException ex) {
            java.util.logging.Logger.getLogger(jOCCIJobControlAdaptor.class.getName()).log(Level.SEVERE, null,
                    ex);
        } catch (AmbiguousIdentifierException ex) {
            java.util.logging.Logger.getLogger(jOCCIJobControlAdaptor.class.getName()).log(Level.SEVERE, null,
                    ex);
        } catch (CommunicationException ex) {
            java.util.logging.Logger.getLogger(jOCCIJobControlAdaptor.class.getName()).log(Level.SEVERE, null,
                    ex);
        }
    } // end creating

    return result;
}

From source file:org.apache.commons.net.examples.telnet.WeatherTelnet.java

public static final void main(String[] args) {
    TelnetClient telnet;

    telnet = new TelnetClient();

    try {//from  w  w w .  j  a v  a2 s . com
        telnet.connect("rainmaker.wunderground.com", 3000);
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
    }

    IOUtil.readWrite(telnet.getInputStream(), telnet.getOutputStream(), System.in, System.out);

    try {
        telnet.disconnect();
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
    }

    System.exit(0);
}