Example usage for java.net Socket getInputStream

List of usage examples for java.net Socket getInputStream

Introduction

In this page you can find the example usage for java.net Socket getInputStream.

Prototype

public InputStream getInputStream() throws IOException 

Source Link

Document

Returns an input stream for this socket.

Usage

From source file:com.vkassin.mtrade.Common.java

public static void login(final Context ctx) {

    // ctx = Common.app_ctx;
    Common.connected = false;/*  ww  w .j a  v  a  2  s  .  c  o  m*/

    if (inLogin)
        return;

    inLogin = true;

    if (Common.mainActivity != null)
        Common.mainActivity.handler.sendMessage(
                Message.obtain(Common.mainActivity.handler, Common.mainActivity.DISMISS_PROGRESS_DIALOG));

    // while(true) {

    final Dialog dialog = new Dialog(ctx);
    dialog.setContentView(R.layout.login_dialog);
    dialog.setTitle(R.string.LoginDialogTitle);
    dialog.setCancelable(false);

    final EditText nametxt = (EditText) dialog.findViewById(R.id.loginnameedit);
    final EditText passtxt = (EditText) dialog.findViewById(R.id.passwordedit);
    final EditText passtxt1 = (EditText) dialog.findViewById(R.id.passwordedit1);
    final EditText passtxt2 = (EditText) dialog.findViewById(R.id.passwordedit2);
    final EditText mailtxt = (EditText) dialog.findViewById(R.id.emailedit2);

    String nam = myaccount.get("name");
    Common.oldName = nam;

    if (nam != null) {

        nametxt.setText(nam);
        passtxt.requestFocus();
    }

    Button customDialog_Register = (Button) dialog.findViewById(R.id.goregister);
    customDialog_Register.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View arg0) {

            dialog.setTitle(R.string.LoginDialogTitle1);
            final LinearLayout layreg = (LinearLayout) dialog.findViewById(R.id.reglayout354);
            layreg.setVisibility(View.VISIBLE);
            final LinearLayout laylog = (LinearLayout) dialog.findViewById(R.id.loginlayout543);
            laylog.setVisibility(View.GONE);
        }

    });

    Button customDialog_Register1 = (Button) dialog.findViewById(R.id.goregister1);
    customDialog_Register1.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View arg0) {

            if (mailtxt.getText().length() < 1) {

                Toast toast = Toast.makeText(mainActivity, R.string.CorrectEmail, Toast.LENGTH_LONG);
                toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0);
                toast.show();

                return;
            }

            if (passtxt1.getText().length() < 1) {

                Toast toast = Toast.makeText(mainActivity, R.string.CorrectPassword, Toast.LENGTH_LONG);
                toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0);
                toast.show();
                return;
            }

            if (!passtxt2.getText().toString().equals(passtxt1.getText().toString())) {

                Toast toast = Toast.makeText(mainActivity, R.string.CorrectPassword1, Toast.LENGTH_LONG);
                toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0);
                toast.show();
                return;
            }

            try {

                Socket sock = new Socket(ip_addr, port_register);

                JSONObject msg = new JSONObject();
                msg.put("objType", Common.MSG_REGISTER);
                msg.put("time", Calendar.getInstance().getTimeInMillis());
                msg.put("user", mailtxt.getText().toString());
                msg.put("passwd", passtxt1.getText().toString());
                msg.put("version", Common.PROTOCOL_VERSION);
                msg.put("sign", sign(mailtxt.getText().toString(), passtxt1.getText().toString()));

                byte[] array = msg.toString().getBytes();
                ByteBuffer buff = ByteBuffer.allocate(array.length + 4);
                buff.putInt(array.length);
                buff.put(array);
                sock.getOutputStream().write(buff.array());

                ByteBuffer buff1 = ByteBuffer.allocate(4);
                buff1.put(readMsg(sock.getInputStream(), 4));
                buff1.position(0);
                int pkgSize = buff1.getInt();
                // Log.i(TAG, "size = "+pkgSize);
                String s = new String(readMsg(sock.getInputStream(), pkgSize));

                sock.close();

                JSONObject jo = new JSONObject(s);

                Log.i(TAG, "register answer = " + jo);

                int t = jo.getInt("status");
                switch (t) {

                case 1:
                    Toast toast = Toast.makeText(mainActivity, R.string.RegisterStatus1, Toast.LENGTH_LONG);
                    toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0);
                    toast.show();

                    dialog.setTitle(R.string.LoginDialogTitle);
                    final LinearLayout layreg = (LinearLayout) dialog.findViewById(R.id.reglayout354);
                    layreg.setVisibility(View.GONE);
                    final LinearLayout laylog = (LinearLayout) dialog.findViewById(R.id.loginlayout543);
                    laylog.setVisibility(View.VISIBLE);

                    nametxt.setText(mailtxt.getText());
                    break;

                case -2:
                    Toast toast1 = Toast.makeText(mainActivity, R.string.RegisterStatus3, Toast.LENGTH_LONG);
                    toast1.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0);
                    toast1.show();
                    break;

                default:
                    Toast toast2 = Toast.makeText(mainActivity, R.string.RegisterStatus2, Toast.LENGTH_LONG);
                    toast2.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0);
                    toast2.show();
                    break;

                }

            } catch (Exception e) {

                e.printStackTrace();
                Log.e(TAG, "Error in registration process!!", e);

                Toast toast = Toast.makeText(mainActivity, R.string.ConnectError, Toast.LENGTH_LONG);
                toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0);
                toast.show();

            }

        }

    });

    Button customDialog_CancelReg = (Button) dialog.findViewById(R.id.cancelreg);
    customDialog_CancelReg.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View arg0) {

            dialog.setTitle(R.string.LoginDialogTitle);
            final LinearLayout layreg = (LinearLayout) dialog.findViewById(R.id.reglayout354);
            layreg.setVisibility(View.GONE);
            final LinearLayout laylog = (LinearLayout) dialog.findViewById(R.id.loginlayout543);
            laylog.setVisibility(View.VISIBLE);

        }

    });

    Button customDialog_Dismiss = (Button) dialog.findViewById(R.id.gologin);
    customDialog_Dismiss.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View arg0) {

            final RadioButton bu0 = (RadioButton) dialog.findViewById(R.id.lradio0);
            Common.isSSL = bu0.isChecked();

            inLogin = false;

            JSONObject msg = new JSONObject();
            try {

                msg.put("objType", Common.LOGOUT);
                msg.put("time", Calendar.getInstance().getTimeInMillis());
                msg.put("version", Common.PROTOCOL_VERSION);
                msg.put("status", 1);
                mainActivity.writeJSONMsg(msg);
            } catch (Exception e) {
                e.printStackTrace();
                Log.e(TAG, "Error! Cannot create JSON logout object", e);
            }

            myaccount.put("name", nametxt.getText().toString());
            myaccount.put("password", passtxt.getText().toString());

            Log.i(TAG,
                    "myaccount username: " + myaccount.get("name") + " password: " + myaccount.get("password"));

            dialog.dismiss();
            mainActivity.stop();
            // saveAccountDetails();
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            loginFromDialog = true;
            //            mainActivity.refresh();

            Common.keypassword(ctx);
        }

    });

    dialog.show();
    // Common.confChanged = false;
    // }//while(true);

}

From source file:com.example.will.sendpic.Camera2BasicFragment.java

private String sendFileGetResult(File file, String url, int port, int secTimeout) {
    Socket s = new Socket();
    String res = "Fail";

    try {//from  w w  w  . j a  va  2s.c o  m
        s.connect(new InetSocketAddress(url, port), secTimeout * 1000);
        DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        FileInputStream fis = new FileInputStream(file);
        byte[] sendBytes = new byte[1024 * 4];
        int len = 0;

        while ((len = fis.read(sendBytes, 0, sendBytes.length)) > 0) {
            dos.write(sendBytes, 0, len);
            dos.flush();
        }
        s.shutdownOutput();

        //get the result from server
        //you can change the protocol
        InputStream in = s.getInputStream();
        byte[] result = new byte[1024];
        int num = in.read(result);

        res = new String(result, 0, num);
        System.out.println(res);

        //closing resources
        s.close();
        dos.close();
        fis.close();
        in.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return res;
}

From source file:NanoHTTPD.java

/**
 * Start the server./*ww w  . j a v a2 s .  co m*/
 *
 * @throws IOException if the socket is in use.
 */
public void start() throws IOException {
    myServerSocket = new ServerSocket();
    myServerSocket
            .bind((hostname != null) ? new InetSocketAddress(hostname, myPort) : new InetSocketAddress(myPort));

    myThread = new Thread(new Runnable() {
        @Override
        public void run() {
            do {
                try {
                    final Socket finalAccept = myServerSocket.accept();
                    registerConnection(finalAccept);
                    finalAccept.setSoTimeout(SOCKET_READ_TIMEOUT);
                    final InputStream inputStream = finalAccept.getInputStream();
                    asyncRunner.exec(new Runnable() {
                        @Override
                        public void run() {
                            OutputStream outputStream = null;
                            try {
                                outputStream = finalAccept.getOutputStream();
                                TempFileManager tempFileManager = tempFileManagerFactory.create();
                                HTTPSession session = new HTTPSession(tempFileManager, inputStream,
                                        outputStream, finalAccept.getInetAddress());
                                while (!finalAccept.isClosed()) {
                                    session.execute();
                                }
                            } catch (Exception e) {
                                // When the socket is closed by the client, we throw our own SocketException
                                // to break the  "keep alive" loop above.
                                if (!(e instanceof SocketException
                                        && "NanoHttpd Shutdown".equals(e.getMessage()))) {
                                    e.printStackTrace();
                                }
                            } finally {
                                safeClose(outputStream);
                                safeClose(inputStream);
                                safeClose(finalAccept);
                                unRegisterConnection(finalAccept);
                            }
                        }
                    });
                } catch (IOException e) {
                }
            } while (!myServerSocket.isClosed());
        }
    });
    myThread.setDaemon(true);
    myThread.setName("NanoHttpd Main Listener");
    myThread.start();
}

From source file:com.google.vrtoolkit.cardboard.samples.treasurehunt.MainActivity.java

private void sendArmoRequest(boolean _lock) {
    final boolean lock = _lock;

    if (lock == false) {
        if (armo_locked == false) {
            return;
        }/* w w  w.  j a v a  2  s. c  o m*/
    }
    if (lock) {
        if (armo_locked == true) {
            return;
        }
    }
    new Thread(new Runnable() {
        public void run() {
            try {
                String host = ARMO_HOST;
                Socket socket = new Socket(host, 5000);
                String request = "GET /position/180 HTTP/1.0\r\n\r\n";
                if (lock == false) {
                    if (armo_locked == false) {
                        return;
                    }
                    armo_locked = false;
                }
                if (lock) {
                    if (armo_locked == true) {
                        return;
                    }
                    request = "GET /position/85 HTTP/1.0\r\n\r\n";
                    armo_locked = true;
                }
                OutputStream os = socket.getOutputStream();
                os.write(request.getBytes());
                os.flush();

                InputStream is = socket.getInputStream();
                int ch;
                while ((ch = is.read()) != -1)
                    System.out.print((char) ch);
                socket.close();
            } catch (IOException e) {
                Log.e("Lock_request", "Something went wrong: " + e.getMessage());
            }
        }
    }).start();
}

From source file:fi.iki.elonen.NanoHTTPD.java

/**
 * Start the server./*from   w  w w .j  av  a2  s .  com*/
 *
 * @throws IOException if the socket is in use.
 */
public void start() throws IOException {
    myServerSocket = new ServerSocket();
    myServerSocket
            .bind((hostname != null) ? new InetSocketAddress(hostname, myPort) : new InetSocketAddress(myPort));

    myThread = new Thread(new Runnable() {
        @Override
        public void run() {
            do {
                try {
                    final Socket finalAccept = myServerSocket.accept();
                    registerConnection(finalAccept);
                    finalAccept.setSoTimeout(SOCKET_READ_TIMEOUT);
                    final InputStream inputStream = finalAccept.getInputStream();
                    if (inputStream == null) {
                        safeClose(finalAccept);
                        unRegisterConnection(finalAccept);
                    } else {
                        asyncRunner.exec(new Runnable() {
                            @Override
                            public void run() {
                                BufferedInputStream bufferedInputStream = null;
                                OutputStream outputStream = null;
                                try {
                                    bufferedInputStream = new BufferedInputStream(inputStream);
                                    outputStream = finalAccept.getOutputStream();
                                    TempFileManager tempFileManager = tempFileManagerFactory.create();
                                    HTTPSession session = new HTTPSession(tempFileManager, bufferedInputStream,
                                            outputStream, finalAccept.getInetAddress());
                                    while (!finalAccept.isClosed()) {
                                        session.execute();
                                    }
                                } catch (Exception e) {
                                    // When the socket is closed by the client, we throw our own SocketException
                                    // to break the  "keep alive" loop above.
                                    if (!(e instanceof SocketException
                                            && "NanoHttpd Shutdown".equals(e.getMessage()))) {
                                        e.printStackTrace();
                                    }
                                } finally {
                                    safeClose(bufferedInputStream);
                                    safeClose(outputStream);
                                    safeClose(finalAccept);
                                    unRegisterConnection(finalAccept);
                                }
                            }
                        });
                    }
                } catch (IOException e) {
                }
            } while (!myServerSocket.isClosed());
        }
    });
    myThread.setDaemon(true);
    myThread.setName("NanoHttpd Main Listener");
    myThread.start();
}

From source file:com.sshtools.appframework.ui.SshToolsApplication.java

public void init(String[] args) throws SshToolsApplicationException {
    instance = this;

    boolean listen = isReuseCapable();

    // Do parse 1 of the command line arguments - see if we need to start
    // the daemon
    Options options1 = new Options();
    SshToolsApplication.this.buildCLIOptions(options1);

    pluginManager = new PluginManager();
    try {/*from w  w w. j  a va  2s.c  o  m*/
        initPluginManager(options1);
    } catch (PluginException e1) {
        log(PluginHostContext.LOG_ERROR, "Failed to initialise plugin manager.", e1);
    }

    CommandLineParser parser1 = new PosixParser();
    CommandLine commandLine1;

    try {
        // parse the command line arguments
        commandLine1 = parser1.parse(options1, args);
        if (commandLine1.hasOption("d")) {
            listen = false;
        }

        if (commandLine1.hasOption('r')) {
            reusePort = Integer.parseInt(commandLine1.getOptionValue('r'));
        }
    } catch (Exception e) {
        // Don't care at the moment
    }

    // Try and message the reuse daemon if possible - saves starting another
    // instance
    if (listen) {
        Socket s = null;
        try {
            String hostname = "localhost";
            if (reusePort == -1) {
                reusePort = getDefaultReusePort();
            }
            log.debug("Attempting connection to reuse server on " + hostname + ":" + reusePort);
            s = new Socket(hostname, reusePort);
            log.debug("Found reuse server on " + hostname + ":" + reusePort + ", sending arguments");
            s.setSoTimeout(5000);
            PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
            for (int i = 0; args != null && i < args.length; i++) {
                pw.println(args[i]);
            }
            pw.println();
            BufferedReader r = new BufferedReader(new InputStreamReader(s.getInputStream()));
            log.debug("Waiting for reuse server reply");
            String error = r.readLine();
            log.debug("Reuse server replied with '" + error + "'");
            if (error != null && !error.equals("")) {
                throw new SshToolsApplicationException(error);
            }
            System.exit(0);
        } catch (SshToolsApplicationException t) {
            throw t;
        } catch (SocketException se) {
            log.debug("No reuse server found.");
        } catch (SocketTimeoutException se) {
            log.debug("Reuse server not responding.", se);
        } catch (Exception e) {
            throw new SshToolsApplicationException(e);
        } finally {
            if (s != null) {
                try {
                    s.close();
                } catch (IOException ioe) {
                }
            }
        }
    }

    additionalOptionsTabs = new ArrayList<OptionsTab>();
    log.info("Initialising application");
    File f = getApplicationPreferencesDirectory();
    if (f != null) {
        //
        FilePreferencesFactory.setPreferencesFile(new File(f, "javaprefs.properties"));
        PreferencesStore.init(new File(f, getApplicationName() + ".properties"));
    }
    setLookAndFeel(getDefaultLAF());

    log.debug("Plugin manager initialised, adding global preferences tabs");

    postInitialization();
    addAdditionalOptionsTab(new GlobalOptionsTab(this));

    Options options = new Options();
    buildCLIOptions(options);
    log.debug("Parsing command line");
    CommandLineParser parser = new PosixParser();
    try {
        // parse the command line arguments
        cli = parser.parse(options, args);
        if (cli.hasOption("?")) {
            printHelp(options);
            System.exit(0);
        }
    } catch (Exception e) {
        System.err.println("Invalid option: " + e.getMessage());
        printHelp(options);
        System.exit(1);
    }
    log.debug("Parsed command line");

    if (listen) {
        Thread t = new Thread("RemoteCommandLine") {
            @Override
            public void run() {
                Socket s = null;
                try {
                    reuseServerSocket = new ServerSocket(reusePort, 1);
                    while (true) {
                        s = reuseServerSocket.accept();
                        BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
                        String line = null;
                        List<String> args = new ArrayList<String>();
                        while ((line = reader.readLine()) != null && !line.equals("")) {
                            args.add(line);
                        }
                        final PrintWriter pw = new PrintWriter(s.getOutputStream());
                        String[] a = new String[args.size()];
                        args.toArray(a);
                        CommandLineParser parser = new PosixParser();
                        Options options = new Options();
                        buildCLIOptions(options);
                        // parse the command line arguments
                        final CommandLine remoteCLI = parser.parse(options, a);
                        pw.println("");
                        SwingUtilities.invokeAndWait(new Runnable() {
                            public void run() {
                                try {
                                    reuseRequest(remoteCLI);
                                } catch (Throwable t) {
                                    pw.println(t.getMessage());
                                }
                            }
                        });
                        s.close();
                        s = null;
                    }
                } catch (Exception e) {
                    /* DEBUG */e.printStackTrace();
                } finally {
                    if (s != null) {
                        try {
                            s.close();
                        } catch (IOException ioe) {

                        }
                    }
                }
            }
        };
        t.setDaemon(true);
        t.start();
    }
}

From source file:com.smartmarmot.dbforbix.config.Config.java

/**
 * Send request to Zabbix Server:/*w  ww .j  av a2  s  .  co m*/
 * @param host - Zabbix Server
 * @param port - Zabbix Server Port
 * @param json - body of request in json format
 * @return - body of response in json format
 */
public String requestZabbix(String host, int port, String json) {
    byte[] response = new byte[2048];
    Socket zabbix = null;
    OutputStreamWriter out = null;
    InputStream in = null;
    byte[] data = null;
    String resp = new String();

    try {
        zabbix = new Socket();
        //TODO socket timeout has to be read from config file
        zabbix.setSoTimeout(30000);

        zabbix.connect(new InetSocketAddress(host, port));
        OutputStream os = zabbix.getOutputStream();

        data = getRequestToZabbixServer(json);

        //send request
        os.write(data);
        os.flush();

        //read response
        in = zabbix.getInputStream();

        //convert response to string (expecting json)
        int pos1 = 13;
        int bRead = 0;
        while (true) {
            bRead = in.read(response);
            //LOG.debug("read="+read+"\nresponse="+new String(response));
            if (bRead <= 0)
                break;
            //remove binary header
            resp += new String(Arrays.copyOfRange(response, pos1, bRead));
            pos1 = 0;
        }
        //LOG.debug("requestZabbix(): resp: "+ resp);
        //resp=resp.substring(13);//remove binary header
        if (resp.isEmpty())
            throw new ZBXBadResponseException("Zabbix Server (" + host + ":" + port
                    + ") has returned empty response for request:\n" + json);

    } catch (ZBXBadResponseException respEx) {
        LOG.error(respEx.getLocalizedMessage());
    } catch (Exception ex) {
        LOG.error("Error getting data from Zabbix server (" + host + ":" + port + "): " + ex.getMessage());
    } finally {
        if (in != null)
            try {
                in.close();
            } catch (IOException e) {
            }
        if (out != null)
            try {
                out.close();
            } catch (IOException e) {
            }
        if (zabbix != null)
            try {
                zabbix.close();
            } catch (IOException e) {
            }
    }

    return resp;
}

From source file:com.atlassian.theplugin.commons.ssl.PluginSSLProtocolSocketFactory.java

/**
 * Copied from AXIS source code,//from  w  ww. j a  va  2 s  . co m
 * original @author Davanum Srinivas (dims@yahoo.com)
 * THIS CODE STILL HAS DEPENDENCIES ON sun.* and com.sun.*
 */
public Socket create(final String host, final int port, final StringBuffer otherHeaders,
        final BooleanHolder useFullURL) throws Exception {

    PluginConfiguration config = ConfigurationFactory.getConfiguration();

    int sslPort = port;
    if (port == -1) {
        sslPort = EasySSLProtocolSocketFactory.SSL_PORT;
    }

    boolean hostInNonProxyList = false;
    TransportClientProperties tcp = TransportClientPropertiesFactory.create("https");

    if (tcp instanceof DefaultHTTPSTransportClientProperties) {
        hostInNonProxyList = ((DefaultHTTPSTransportClientProperties) tcp).getNonProxyHosts().contains("host");
    }
    //boolean hostInNonProxyList = super.isHostInNonPxyList(host, tcp.getNonProxyHosts());

    Socket sslSocket;
    if (!config.getGeneralConfigurationData().getUseIdeaProxySettings() || hostInNonProxyList
            || tcp.getProxyHost().length() == 0) {
        // direct SSL connection
        sslSocket = super.createSocket(host, sslPort);
    } else {
        int tunnelPort = (tcp.getProxyPort().length() != 0) ? Integer.parseInt(tcp.getProxyPort())
                : DEFAULT_PROXY_PORT;
        if (tunnelPort < 0) {
            tunnelPort = DEFAULT_PROXY_PORT;
        }

        // Create the regular socket connection to the proxy
        //Socket l = new Socket(new InetAddressImpl(tcp.getProxyHost()), tunnelPort);
        Socket tunnel = new Socket(InetAddress.getByName(tcp.getProxyHost()), tunnelPort);

        // The tunnel handshake method (condensed and made reflexive)
        OutputStream tunnelOutputStream = tunnel.getOutputStream();
        PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(tunnelOutputStream)));

        // More secure version... engage later?
        // PasswordAuthentication pa =
        // Authenticator.requestPasswordAuthentication(
        // InetAddress.getByName(tunnelHost),
        // tunnelPort, "SOCK", "Proxy","HTTP");
        // if(pa == null){
        // printDebug("No Authenticator set.");
        // }else{
        // printDebug("Using Authenticator.");
        // tunnelUser = pa.getUserName();
        // tunnelPassword = new String(pa.getPassword());
        // }
        out.print("CONNECT " + host + ":" + sslPort + " HTTP/1.0\r\n" + "User-Agent: AxisClient");
        if (tcp.getProxyUser().length() != 0 && tcp.getProxyPassword().length() != 0) {

            // add basic authentication header for the proxy
            String encodedPassword = XMLUtils
                    .base64encode((tcp.getProxyUser() + ":" + tcp.getProxyPassword()).getBytes());

            out.print("\nProxy-Authorization: Basic " + encodedPassword);
        }
        out.print("\nContent-Length: 0");
        out.print("\nPragma: no-cache");
        out.print("\r\n\r\n");
        out.flush();
        InputStream tunnelInputStream = tunnel.getInputStream();

        if (logger != null) {
            logger.debug(
                    Messages.getMessage("isNull00", "tunnelInputStream", "" + (tunnelInputStream == null)));
        }

        String replyStr = "";

        // Make sure to read all the response from the proxy to prevent SSL negotiation failure
        // Response message terminated by two sequential newlines
        int newlinesSeen = 0;
        boolean headerDone = false; /* Done on first newline */

        while (newlinesSeen < 2) {
            int i = tunnelInputStream.read();

            if (i < 0) {
                throw new IOException("Unexpected EOF from proxy");
            }
            if (i == '\n') {
                headerDone = true;
                ++newlinesSeen;
            } else if (i != '\r') {
                newlinesSeen = 0;
                if (!headerDone) {
                    replyStr += String.valueOf((char) i);
                }
            }
        }
        if (!StringUtils.startsWithIgnoreWhitespaces("HTTP/1.0 200", replyStr)
                && !StringUtils.startsWithIgnoreWhitespaces("HTTP/1.1 200", replyStr)) {
            throw new IOException(Messages.getMessage("cantTunnel00",
                    new String[] { tcp.getProxyHost(), "" + tunnelPort, replyStr }));
        }

        // End of condensed reflective tunnel handshake method
        sslSocket = super.createSocket(tunnel, host, port, true);

        if (logger != null) {
            logger.debug(Messages.getMessage("setupTunnel00", tcp.getProxyHost(), "" + tunnelPort));
        }

    }

    ((SSLSocket) sslSocket).startHandshake();
    if (logger != null) {
        logger.debug(Messages.getMessage("createdSSL00"));
    }
    return sslSocket;
}

From source file:com.jcraft.weirdx.WeirdX.java

public void weirdx_start(Container container) throws ConnectException {
    if (xdmcpmode != null) {
        LOG.debug("XDMC Mode = " + xdmcpmode);
        if (xdmcpmode.equals("query")) {
            xdmcp = new XDMCP(xdmcpaddr, myAddress, displayNumber);
        } else if (xdmcpmode.equals("broadcast")) {
            xdmcp = new XDMCP(XDMCP.BroadcastQuery, xdmcpaddr, myAddress, displayNumber);
        } else if (xdmcpmode.equals("indirect")) {
            xdmcp = new XDMCP(XDMCP.IndirectQuery, xdmcpaddr, myAddress, displayNumber);
        }/*w w  w .ja va 2  s  . c o m*/
    }

    if (sxrexec != null && sxrexec.equals("yes")) {
        xrexec = new XRexec(myAddress, displayNumber);
    }

    weirdx_init(container);

    InputStream in;
    OutputStream out;

    InputOutput client = null;

    if (xdmcp != null) {
        Client.addListener((ClientListener) xdmcp);
        xdmcp.start();
    }

    if (jdxpc != null) {
        (new SpawnJDxpc(this)).start();
    }
    if (ssshrexec != null) {
        if (ssshrexec.equals("yes")) {
            (new SpawnSSHRexec(this)).start();
        }
    }

    byte[] byte_order = new byte[1];
    try {
        Socket socket = null;
        while (true && weirdx != null) {
            try {
                socket = displaysocket.accept();
            } catch (Exception e) {
                LOG.error(e);
                if (e instanceof NullPointerException) {
                    weirdx = null;
                    break;
                }
                continue;
            }

            if (!Acl.check(socket.getInetAddress())) {
                LOG.error("ACL warning: unauthorized access from " + socket.getInetAddress());
                try {
                    socket.close();
                } catch (Exception e) {
                }
                ;
                continue;
            }

            try {
                socket.setTcpNoDelay(true);
            } catch (Exception eeee) {
                //System.out.println(eeee+" tcpnodelay");
            }

            client = null;

            in = socket.getInputStream();
            out = socket.getOutputStream();

            try {
                in.read(byte_order, 0, 1);
            } catch (Exception e) {
                continue;
            }

            // 0x6c LSB
            // 0x42 MSB
            if (byte_order[0] == 0x6c) {
                client = new IOLSB();
            } else if (byte_order[0] == 0x42) {
                client = new IOMSB();
            } else {
                LOG.warn("protocol: error " + Integer.toHexString(byte_order[0]));
                continue;
            }

            client.setInputStream(in);
            client.setOutputStream(out);

            Client foo = new Client(client);
            if (foo.index != -1) {
                foo.start();
            } else {
                // System.err.println("running over clients table");
            }
        }
    } catch (IOException e) {
        LOG.error("IO Error: " + e.getLocalizedMessage());
    }
    // stop(); // ??
}

From source file:io.undertow.server.handlers.sse.ServerSentEventTestCase.java

@Test
public void testConnectionFail() throws IOException, InterruptedException {

    final Socket socket = new Socket(DefaultServer.getHostAddress("default"),
            DefaultServer.getHostPort("default"));
    final CountDownLatch latch = new CountDownLatch(1);
    final CountDownLatch connected = new CountDownLatch(1);
    DefaultServer.setRootHandler(new ServerSentEventHandler(new ServerSentEventConnectionCallback() {
        @Override/*from  w  w w.  j av a  2  s .c om*/
        public void connected(final ServerSentEventConnection connection, final String lastEventId) {
            final XnioIoThread thread = (XnioIoThread) Thread.currentThread();
            connected.countDown();
            thread.execute(new Runnable() {
                @Override
                public void run() {
                    connection.send("hello", new ServerSentEventConnection.EventCallback() {
                        @Override
                        public void done(ServerSentEventConnection connection, String data, String event,
                                String id) {
                        }

                        @Override
                        public void failed(ServerSentEventConnection connection, String data, String event,
                                String id, IOException e) {
                            latch.countDown();
                        }
                    });
                    if (latch.getCount() > 0) {
                        WorkerUtils.executeAfter(thread, this, 100, TimeUnit.MILLISECONDS);
                    }
                }
            });
        }
    }));
    InputStream in = socket.getInputStream();
    OutputStream out = socket.getOutputStream();
    out.write(("GET / HTTP/1.1\r\nHost:" + DefaultServer.getHostAddress() + "\r\n\r\n").getBytes());
    out.flush();
    if (!connected.await(10, TimeUnit.SECONDS)) {
        Assert.fail();
    }
    out.close();
    in.close();
    if (!latch.await(10, TimeUnit.SECONDS)) {
        Assert.fail();
    }
}