Example usage for java.net Socket getOutputStream

List of usage examples for java.net Socket getOutputStream

Introduction

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

Prototype

public OutputStream getOutputStream() throws IOException 

Source Link

Document

Returns an output stream for this socket.

Usage

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   www  . ja  v a 2 s  . co 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:com.hijacker.MainActivity.java

static void checkForUpdate(final Activity activity, final boolean showMessages) {
    //Can be called from any thread, blocks until the job is finished
    Runnable runnable = new Runnable() {
        @Override/* w w w  .j a v  a 2s .com*/
        public void run() {
            progress.setIndeterminate(false);
        }
    };
    if (showMessages) {
        runInHandler(new Runnable() {
            @Override
            public void run() {
                progress.setIndeterminate(true);
            }
        });
    }
    Socket socket = connect();
    if (socket == null) {
        if (showMessages) {
            runInHandler(runnable);
            Snackbar.make(rootView, activity.getString(R.string.server_error), Snackbar.LENGTH_SHORT).show();
        }
        return;
    }

    try {
        PrintWriter in = new PrintWriter(socket.getOutputStream());
        BufferedReader out = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        in.print(REQ_VERSION + '\n');
        in.flush();

        int latestCode = Integer.parseInt(out.readLine());
        String latestName = out.readLine();
        String latestLink = out.readLine();

        in.print(REQ_EXIT + '\n');
        in.flush();
        in.close();
        out.close();
        socket.close();

        if (latestCode > versionCode) {
            final UpdateConfirmDialog dialog = new UpdateConfirmDialog();
            dialog.newVersionCode = latestCode;
            dialog.newVersionName = latestName;
            dialog.link = latestLink;
            runInHandler(new Runnable() {
                @Override
                public void run() {
                    dialog.show(activity.getFragmentManager(), "UpdateConfirmDialog");
                }
            });
        } else {
            if (showMessages)
                Snackbar.make(rootView, activity.getString(R.string.already_on_latest), Snackbar.LENGTH_SHORT)
                        .show();
        }
    } catch (IOException | NumberFormatException e) {
        Log.e("HIJACKER/update", e.toString());
        if (showMessages)
            Snackbar.make(rootView, activity.getString(R.string.unknown_error), Snackbar.LENGTH_SHORT).show();
    } finally {
        if (showMessages)
            runInHandler(runnable);
    }
}

From source file:com.clavain.munin.MuninNode.java

private void updateTrackPackages(Socket p_socket) {
    // only try to update this once per hour
    int curTime = getUnixtime();
    int lalert = this.last_pkg_update + 3600;
    if (lalert > curTime) {
        return;/*from w w w . ja  va 2 s  .c o m*/
    }

    String decodestr = "";
    try {
        logger.info("TrackPackages - fetching " + this.str_hostname);
        PrintStream os = new PrintStream(p_socket.getOutputStream());
        BufferedReader in = new BufferedReader(new InputStreamReader(p_socket.getInputStream()));
        os.println("config muninmx_trackpkg");
        // skip first line if starts with #
        decodestr = in.readLine();
        if (decodestr.startsWith("#")) {
            decodestr = in.readLine();
        }

        if (decodestr.equals(".")) {
            decodestr = in.readLine();
        }
        byte[] decode = Base64.decodeBase64(decodestr);
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(decode);
        GZIPInputStream gzipInputStream;
        gzipInputStream = new GZIPInputStream(byteArrayInputStream);

        InputStreamReader inputStreamReader = new InputStreamReader(gzipInputStream);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader, 4);

        String read;
        String sum = bufferedReader.readLine();
        if (sum == null) {
            logger.error("TrackPackages - sum is null for: " + this.str_hostname);
            return;
        }
        String dist = bufferedReader.readLine();
        String ver = bufferedReader.readLine();
        String kernel = bufferedReader.readLine();
        if (dbTrackLogChangedForNode(sum, this.node_id)) {
            logger.info("TrackPackages - packages changed, updating " + this.str_hostname);
            // purge old logs
            removeOldPackageTrack(this.node_id);

            dbUpdateNodeDistVerKernel(sum, dist, ver, kernel, this.node_id);
            int i = 0;
            while ((read = bufferedReader.readLine()) != null) {
                BasicDBObject doc = new BasicDBObject();
                doc.put("package", read);
                doc.put("time", getUnixtime());
                doc.put("node", this.node_id);
                doc.put("type", "trackpkg");
                com.clavain.muninmxcd.mongo_essential_queue.add(doc);
                i++;
            }
            logger.info("TrackPackages Updated for Node: " + this.getHostname() + " (" + dist + " " + ver + " "
                    + kernel + "). tracking " + i + " packages");
        } else {
            logger.info("TrackPackages - sum not changed since last run for Node: " + this.getHostname());
        }
        this.last_pkg_update = getUnixtime();

    } catch (Exception ex) {
        logger.error("Error in updateTrackPackages for Node " + this.getHostname() + " : "
                + ex.getLocalizedMessage());
        logger.error("updateTrackPackages for Node " + this.getHostname() + " received: " + decodestr);
        ex.printStackTrace();
    }

}

From source file:com.cbsb.ftpserv.ProxyConnector.java

/**
 * Connects an outgoing socket to the proxy and authenticates, creating an account
 * if necessary.//from   w  w  w.j  a v a2s .c o m
 */
private Socket newAuthedSocket(String hostname, int port) {
    if (hostname == null) {
        myLog.i("newAuthedSocket can't connect to null host");
        return null;
    }
    JSONObject json = new JSONObject();
    //String secret = retrieveSecret();
    Socket socket;
    OutputStream out = null;
    InputStream in = null;

    try {
        myLog.d("Opening proxy connection to " + hostname + ":" + port);
        socket = new Socket();
        socket.connect(new InetSocketAddress(hostname, port), CONNECT_TIMEOUT);
        json.put("android_id", Util.getAndroidId());
        json.put("swiftp_version", Util.getVersion());
        json.put("action", "login");
        out = socket.getOutputStream();
        in = socket.getInputStream();
        int numBytes;

        out.write(json.toString().getBytes(ENCODING));
        myLog.l(Log.DEBUG, "Sent login request");
        // Read and parse the server's response
        byte[] bytes = new byte[IN_BUF_SIZE];
        // Here we assume that the server's response will all be contained in
        // a single read, which may be unsafe for large responses
        numBytes = in.read(bytes);
        if (numBytes == -1) {
            myLog.l(Log.INFO, "Proxy socket closed while waiting for auth response");
            return null;
        } else if (numBytes == 0) {
            myLog.l(Log.INFO, "Short network read waiting for auth, quitting");
            return null;
        }
        json = new JSONObject(new String(bytes, 0, numBytes, ENCODING));
        if (checkAndPrintJsonError(json)) {
            return null;
        }
        myLog.d("newAuthedSocket successful");
        return socket;
    } catch (Exception e) {
        myLog.i("Exception during proxy connection or authentication: " + e);
        return null;
    }
}

From source file:it.jnrpe.client.JNRPEClient.java

/**
 * Inovoke a command installed in JNRPE.
 * /*www.j a  va2  s  .com*/
 * @param sCommandName
 *            The name of the command to be invoked
 * @param arguments
 *            The arguments to pass to the command (will substitute the
 *            $ARGSx$ parameters)
 * @return The value returned by the server
 * @throws JNRPEClientException
 *             Thrown on any communication error.
 */
public final ReturnValue sendCommand(final String sCommandName, final String... arguments)
        throws JNRPEClientException {
    SocketFactory socketFactory;

    Socket s = null;
    try {
        if (!useSSL) {
            socketFactory = SocketFactory.getDefault();
        } else {
            SSLContext sslContext = SSLContext.getInstance("TLSv1.2");

            sslContext.init(null, new TrustManager[] { getTrustManager() }, new SecureRandom());

            socketFactory = sslContext.getSocketFactory();
        }

        s = socketFactory.createSocket();
        if (weakCipherSuitesEnabled) {
            SSLSocket ssl = (SSLSocket) s;
            ssl.setEnabledCipherSuites(ssl.getSupportedCipherSuites());
        }

        s.setSoTimeout((int) TimeUnit.SECOND.convert(communicationTimeout));
        s.connect(new InetSocketAddress(serverIPorURL, serverPort));
        JNRPERequest req = new JNRPERequest(sCommandName, arguments);

        s.getOutputStream().write(req.toByteArray());

        InputStream in = s.getInputStream();
        JNRPEResponse res = new JNRPEResponse(in);

        return new ReturnValue(Status.fromIntValue(res.getResultCode()), res.getMessage());
    } catch (RuntimeException re) {
        throw re;
    } catch (Exception e) {
        throw new JNRPEClientException(e);
    } finally {
        if (s != null) {
            try {
                s.close();
            } catch (IOException e) {
                // Ignore
            }
        }
    }
}

From source file:com.cong.chenchong.wifi.manager.ProxyConnector.java

/**
 * Connects an outgoing socket to the proxy and authenticates, creating an account
 * if necessary.// ww w  .  j a v a 2s .  c  o  m
 */
private Socket newAuthedSocket(String hostname, int port) {
    if (hostname == null) {
        //myLog.i("newAuthedSocket can't connect to null host");
        return null;
    }
    JSONObject json = new JSONObject();
    //String secret = retrieveSecret();
    Socket socket;
    OutputStream out = null;
    InputStream in = null;

    try {
        //myLog.d("Opening proxy connection to " + hostname + ":" + port);
        socket = new Socket();
        socket.connect(new InetSocketAddress(hostname, port), CONNECT_TIMEOUT);
        json.put("android_id", RemoteUtil.getAndroidId());
        json.put("swiftp_version", RemoteUtil.getVersion());
        json.put("action", "login");
        out = socket.getOutputStream();
        in = socket.getInputStream();
        int numBytes;

        out.write(json.toString().getBytes(ENCODING));
        //myLog.l(Log.DEBUG, "Sent login request");
        // Read and parse the server's response
        byte[] bytes = new byte[IN_BUF_SIZE];
        // Here we assume that the server's response will all be contained in
        // a single read, which may be unsafe for large responses
        numBytes = in.read(bytes);
        if (numBytes == -1) {
            //myLog.l(Log.INFO, "Proxy socket closed while waiting for auth response");
            return null;
        } else if (numBytes == 0) {
            //myLog.l(Log.INFO, "Short network read waiting for auth, quitting");
            return null;
        }
        json = new JSONObject(new String(bytes, 0, numBytes, ENCODING));
        if (checkAndPrintJsonError(json)) {
            return null;
        }
        //myLog.d("newAuthedSocket successful");
        return socket;
    } catch (Exception e) {
        //myLog.i("Exception during proxy connection or authentication: " + e);
        return null;
    }
}

From source file:com.clustercontrol.agent.Agent.java

/**
 * ??sendManagerDiscoveryInfo?// w w w .j  a va2  s.c  o m
 * TCP 24005?????????IP?
 * 
 * @throws Exception
 */
private String receiveManagerDiscoveryInfo() throws Exception {
    int default_port = 24005;
    String portStr = AgentProperties.getProperty("discovery.pingport", Integer.toString(default_port));
    int port = Integer.parseInt(portStr);
    if (port < 1 || port > 65535) {
        port = default_port;
    }
    ServerSocket servSock = null;
    Socket clntSock = null;

    final int BUFSIZE = 256;
    int tmpRecvMsgSize = 0;
    int recvMsgSize = 0;
    byte[] receiveBuf = new byte[BUFSIZE];
    String recvMsg = "";

    try {
        servSock = new ServerSocket(port);

        // ????
        clntSock = servSock.accept();
        m_log.info("connecting to " + clntSock.getRemoteSocketAddress().toString());

        InputStream in = clntSock.getInputStream();
        OutputStream out = clntSock.getOutputStream();

        while ((tmpRecvMsgSize = in.read(receiveBuf)) != -1) {
            out.write(receiveBuf, 0, tmpRecvMsgSize);
            recvMsgSize = tmpRecvMsgSize;
        }

        recvMsg = new String(receiveBuf, 0, recvMsgSize);
        m_log.info("receive message : " + recvMsg);
    } catch (Exception e) {
        m_log.warn("receiveManagerIp " + e.getClass().getSimpleName() + ", " + e.getMessage());
        throw e;
    } finally {
        try {
            if (clntSock != null) {
                clntSock.close();
            }
        } catch (Exception e) {
            m_log.warn("receiveManagerIp: " + e);
        }
        try {
            if (servSock != null) {
                servSock.close();
            }
        } catch (Exception e) {
            m_log.warn("receiveManagerIp: " + e);
        }
    }
    return recvMsg;
}

From source file:com.web.services.ExecutorServiceThread.java

public void run() {

    // create a selector that will by used for multiplexing. The selector
    // registers the socketserverchannel as
    // well as all socketchannels that are created
    String CLIENTCHANNELNAME = "clientChannel";
    String SERVERCHANNELNAME = "serverChannel";
    String channelType = "channelType";

    ConcurrentHashMap<SelectionKey, Object> resultMap = new ConcurrentHashMap<SelectionKey, Object>();
    ClassLoader classLoader = null;
    ByteArrayOutputStream bstr;/*  w  w w  .j a  v a  2s .  co m*/
    ByteBuffer buffer = null;
    ByteBuffer lengthBuffer = ByteBuffer.allocate(4);
    int bytesRead;
    InputStream bais;
    ObjectInputStream ois;
    Object object;
    ExecutorServiceInfo executorServiceInfo = null;
    Random random = new Random(System.currentTimeMillis());
    // register the serversocketchannel with the selector. The OP_ACCEPT
    // option marks
    // a selection key as ready when the channel accepts a new connection.
    // When the
    // socket server accepts a connection this key is added to the list of
    // selected keys of the selector.
    // when asked for the selected keys, this key is returned and hence we
    // know that a new connection has been accepted.
    try {
        Selector selector = Selector.open();
        SelectionKey socketServerSelectionKey = serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        // SelectionKey socketServerSelectionKey1 =
        // channel.register(selector1,
        // SelectionKey.OP_ACCEPT);

        // set property in the key that identifies the channel
        Map<String, String> properties = new ConcurrentHashMap<String, String>();
        properties.put(channelType, SERVERCHANNELNAME);
        socketServerSelectionKey.attach(properties);
        // wait for the selected keys
        SelectionKey key = null;
        Set<SelectionKey> selectedKeys;
        // logger.info("Instance Number"+instanceNumber);
        Iterator<SelectionKey> iterator = null;
        SocketChannel clientChannel = null;
        while (true) {
            try {
                // the select method is a blocking method which returns when
                // atleast
                // one of the registered
                // channel is selected. In this example, when the socket
                // accepts
                // a
                // new connection, this method
                // will return. Once a socketclient is added to the list of
                // registered channels, then this method
                // would also return when one of the clients has data to be
                // read
                // or
                // written. It is also possible to perform a nonblocking
                // select
                // using the selectNow() function.
                // We can also specify the maximum time for which a select
                // function
                // can be blocked using the select(long timeout) function.

                if (selector.select() >= 0) {
                    selectedKeys = selector.selectedKeys();
                    iterator = selectedKeys.iterator();
                }
                while (iterator.hasNext()) {
                    try {
                        key = iterator.next();
                        // the selection key could either by the
                        // socketserver
                        // informing
                        // that a new connection has been made, or
                        // a socket client that is ready for read/write
                        // we use the properties object attached to the
                        // channel
                        // to
                        // find
                        // out the type of channel.
                        if (((Map) key.attachment()).get(channelType).equals(SERVERCHANNELNAME)) {
                            // a new connection has been obtained. This
                            // channel
                            // is
                            // therefore a socket server.
                            ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
                            // accept the new connection on the server
                            // socket.
                            // Since
                            // the
                            // server socket channel is marked as non
                            // blocking
                            // this channel will return null if no client is
                            // connected.
                            SocketChannel clientSocketChannel = serverSocketChannel.accept();

                            if (clientSocketChannel != null) {
                                // set the client connection to be non
                                // blocking
                                clientSocketChannel.configureBlocking(false);
                                SelectionKey clientKey = clientSocketChannel.register(selector,
                                        SelectionKey.OP_READ, SelectionKey.OP_WRITE);
                                Map<String, String> clientproperties = new ConcurrentHashMap<String, String>();
                                clientproperties.put(channelType, CLIENTCHANNELNAME);
                                clientKey.attach(clientproperties);
                                clientKey.interestOps(SelectionKey.OP_READ);
                                // clientSocketChannel.close();
                                // write something to the new created client
                                /*
                                 * CharBuffer buffer =
                                 * CharBuffer.wrap("Hello client"); while
                                 * (buffer.hasRemaining()) {
                                 * clientSocketChannel.write
                                 * (Charset.defaultCharset()
                                 * .encode(buffer)); }
                                 * clientSocketChannel.close();
                                 * buffer.clear();
                                 */
                            }

                        } else {
                            // data is available for read
                            // buffer for reading
                            clientChannel = (SocketChannel) key.channel();
                            if (key.isReadable()) {
                                // the channel is non blocking so keep it
                                // open
                                // till
                                // the
                                // count is >=0
                                clientChannel = (SocketChannel) key.channel();
                                if (resultMap.get(key) == null) {
                                    //System.out.println(key);
                                    bstr = new ByteArrayOutputStream();
                                    object = null;
                                    clientChannel.read(lengthBuffer);
                                    int length = lengthBuffer.getInt(0);
                                    lengthBuffer.clear();
                                    //System.out.println(length);
                                    buffer = ByteBuffer.allocate(length);
                                    if ((bytesRead = clientChannel.read(buffer)) > 0) {
                                        // buffer.flip();
                                        // System.out
                                        // .println(bytesRead);
                                        bstr.write(buffer.array(), 0, bytesRead);
                                        buffer.clear();
                                    }
                                    buffer.clear();
                                    //System.out.println("Message1"+new String(bstr
                                    //      .toByteArray()));
                                    bais = new ByteArrayInputStream(bstr.toByteArray());
                                    ois = new ObjectInputStream(bais); // Offending
                                    // line.
                                    // Produces
                                    // the
                                    // StreamCorruptedException.
                                    //System.out.println("In read obect");
                                    object = ois.readObject();
                                    //System.out.println("Class Cast");
                                    //System.out.println("Class Cast1");
                                    ois.close();
                                    byte[] params = bstr.toByteArray();
                                    bstr.close();
                                    //System.out.println("readObject");
                                    //System.out.println("After readObject");
                                    if (object instanceof CloseSocket) {
                                        resultMap.remove(key);
                                        clientChannel.close();
                                        key.cancel();
                                    }
                                    // clientChannel.close();
                                    String serviceurl = (String) object;
                                    String[] serviceRegistry = serviceurl.split("/");
                                    //System.out.println("classLoaderMap"
                                    //      + urlClassLoaderMap);
                                    //System.out.println(deployDirectory
                                    //      + "/" + serviceRegistry[0]);

                                    int servicenameIndex;
                                    //System.out.println(earServicesDirectory
                                    //      + "/" + serviceRegistry[0]
                                    //      + "/" + serviceRegistry[1]);
                                    if (serviceRegistry[0].endsWith(".ear")) {
                                        classLoader = (VFSClassLoader) urlClassLoaderMap
                                                .get(earServicesDirectory + "/" + serviceRegistry[0] + "/"
                                                        + serviceRegistry[1]);
                                        servicenameIndex = 2;
                                    } else if (serviceRegistry[0].endsWith(".jar")) {
                                        classLoader = (WebClassLoader) urlClassLoaderMap
                                                .get(jarservicesDirectory + "/" + serviceRegistry[0]);
                                        servicenameIndex = 1;
                                    } else {
                                        classLoader = (WebClassLoader) urlClassLoaderMap
                                                .get(deployDirectory + "/" + serviceRegistry[0]);
                                        servicenameIndex = 1;
                                    }
                                    String serviceName = serviceRegistry[servicenameIndex];
                                    // System.out.println("servicename:"+serviceName);;
                                    synchronized (executorServiceMap) {
                                        executorServiceInfo = (ExecutorServiceInfo) executorServiceMap
                                                .get(serviceName.trim());
                                    }
                                    ExecutorServiceInfoClassLoader classLoaderExecutorServiceInfo = new ExecutorServiceInfoClassLoader();
                                    classLoaderExecutorServiceInfo.setClassLoader(classLoader);
                                    classLoaderExecutorServiceInfo.setExecutorServiceInfo(executorServiceInfo);
                                    resultMap.put(key, classLoaderExecutorServiceInfo);
                                    // key.interestOps(SelectionKey.OP_READ);
                                    // System.out.println("Key interested Ops");
                                    // continue;
                                }
                                //Thread.sleep(100);
                                /*
                                 * if (classLoader == null) throw new
                                 * Exception(
                                 * "Could able to obtain deployed class loader"
                                 * );
                                 */
                                /*
                                 * System.out.println(
                                 * "current context classloader" +
                                 * classLoader);
                                 */
                                //System.out.println("In rad object");
                                bstr = new ByteArrayOutputStream();
                                lengthBuffer.clear();
                                int numberofDataRead = clientChannel.read(lengthBuffer);
                                //System.out.println("numberofDataRead"
                                //      + numberofDataRead);
                                int length = lengthBuffer.getInt(0);
                                if (length <= 0) {
                                    iterator.remove();
                                    continue;
                                }
                                lengthBuffer.clear();
                                //System.out.println(length);
                                buffer = ByteBuffer.allocate(length);
                                buffer.clear();
                                if ((bytesRead = clientChannel.read(buffer)) > 0) {
                                    // buffer.flip();
                                    // System.out
                                    // .println(bytesRead);
                                    bstr.write(buffer.array(), 0, bytesRead);
                                    buffer.clear();
                                }
                                if (bytesRead <= 0 || bytesRead < length) {
                                    //System.out.println("bytesRead<length");
                                    iterator.remove();
                                    continue;
                                }
                                //System.out.println(new String(bstr
                                //   .toByteArray()));
                                bais = new ByteArrayInputStream(bstr.toByteArray());

                                ExecutorServiceInfoClassLoader classLoaderExecutorServiceInfo = (ExecutorServiceInfoClassLoader) resultMap
                                        .get(key);
                                ois = new ClassLoaderObjectInputStream(
                                        (ClassLoader) classLoaderExecutorServiceInfo.getClassLoader(), bais); // Offending
                                // line.
                                // Produces
                                // the
                                // StreamCorruptedException.
                                object = ois.readObject();
                                ois.close();
                                bstr.close();
                                executorServiceInfo = classLoaderExecutorServiceInfo.getExecutorServiceInfo();
                                //System.out
                                //      .println("inputStream Read Object");
                                //System.out.println("Object="
                                //      + object.getClass());
                                // Thread.currentThread().setContextClassLoader(currentContextLoader);
                                if (object instanceof ExecutorParams) {
                                    ExecutorParams exeParams = (ExecutorParams) object;
                                    Object returnValue = null;

                                    //System.out.println("test socket1");
                                    String ataKey;
                                    ATAConfig ataConfig;
                                    ConcurrentHashMap ataServicesMap;

                                    ATAExecutorServiceInfo servicesAvailable;
                                    Socket sock1 = new Socket("0.0.0.0",
                                            Integer.parseInt(nodesport[random.nextInt(nodesport.length)]));
                                    OutputStream outputStr = sock1.getOutputStream();
                                    ObjectOutputStream objOutputStream = new ObjectOutputStream(outputStr);
                                    NodeInfo nodeInfo = new NodeInfo();
                                    nodeInfo.setClassNameWithPackage(
                                            executorServiceInfo.getExecutorServicesClass().getName());
                                    nodeInfo.setMethodName(executorServiceInfo.getMethod().getName());

                                    nodeInfo.setWebclassLoaderURLS(((WebClassLoader) classLoader).geturlS());
                                    NodeInfoMethodParam nodeInfoMethodParam = new NodeInfoMethodParam();
                                    nodeInfoMethodParam.setMethodParams(exeParams.getParams());
                                    nodeInfoMethodParam
                                            .setMethodParamTypes(executorServiceInfo.getMethodParams());
                                    //System.out.println("Serializable socket="+sock);
                                    //nodeInfo.setSock(sock);
                                    //nodeInfo.setOstream(sock.getOutputStream());
                                    objOutputStream.writeObject(nodeInfo);
                                    objOutputStream = new ObjectOutputStream(outputStr);
                                    objOutputStream.writeObject(nodeInfoMethodParam);
                                    ObjectInputStream objInputStream1 = new ObjectInputStream(
                                            sock1.getInputStream());
                                    returnValue = objInputStream1.readObject();
                                    objOutputStream.close();
                                    objInputStream1.close();
                                    sock1.close();
                                    /*returnValue = executorServiceInfo
                                          .getMethod()
                                          .invoke(executorServiceInfo
                                                .getExecutorServicesClass()
                                                .newInstance(),
                                                exeParams.getParams());*/
                                    // Thread.currentThread().setContextClassLoader(oldCL);

                                    //   System.out.println("Written Value="
                                    //         + returnValue.toString());
                                    resultMap.put(key, returnValue);
                                }
                                key.interestOps(SelectionKey.OP_WRITE);
                                //System.out.println("Key interested Ops1");
                            } else if (key.isWritable()) {
                                // the channel is non blocking so keep it
                                // open
                                // till the
                                // count is >=0
                                //System.out.println("In write");
                                ByteArrayOutputStream baos = new ByteArrayOutputStream(); // make
                                // a
                                // BAOS
                                // stream
                                ObjectOutputStream oos = new ObjectOutputStream(baos); // wrap and OOS around the
                                                                                       // stream
                                Object result = resultMap.get(key);
                                oos.writeObject(result); // write an object
                                // to
                                // the stream
                                oos.flush();
                                oos.close();
                                byte[] objData = baos.toByteArray(); // get
                                // the
                                // byte
                                // array
                                baos.close();
                                buffer = ByteBuffer.wrap(objData); // wrap
                                // around
                                // the
                                // data
                                buffer.rewind();
                                // buffer.flip(); //prep for writing
                                //System.out.println(new String(objData));
                                //while (buffer.hasRemaining())
                                clientChannel.write(buffer); // write
                                resultMap.remove(key);
                                buffer.clear();
                                key.cancel();
                                clientChannel.close();
                                //System.out.println("In write1");
                                numberOfServicesRequests++;
                                //System.out.println("Key interested Ops2");
                            }

                        }

                        iterator.remove();
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        key.cancel();
                        clientChannel.close();
                        resultMap.remove(key);
                        //ex.printStackTrace();
                    }

                }

            } catch (Exception ex) {

                //ex.printStackTrace();
            }
        }
    } catch (Exception ex) {
        //ex.printStackTrace();
    }
}

From source file:android.core.SSLSocketTest.java

/**
 * Does a number of HTTPS requests on some host and consumes the response.
 * We don't use the HttpsUrlConnection class, but do this on our own
 * with the SSLSocket class. This gives us a chance to test the basic
 * behavior of SSL.//from ww  w  . ja v  a 2s. c o  m
 *
 * @param host      The host name the request is being sent to.
 * @param port      The port the request is being sent to.
 * @param path      The path being requested (e.g. "/index.html").
 * @param outerLoop The number of times we reconnect and do the request.
 * @param innerLoop The number of times we do the request for each
 *                  connection (using HTTP keep-alive).
 * @param delay     The delay after each request (in seconds).
 * @throws IOException When a problem occurs.
 */
private void fetch(SSLSocketFactory socketFactory, String host, int port, boolean secure, String path,
        int outerLoop, int innerLoop, int delay, int timeout) throws IOException {
    InetSocketAddress address = new InetSocketAddress(host, port);

    for (int i = 0; i < outerLoop; i++) {
        // Connect to the remote host
        Socket socket = secure ? socketFactory.createSocket() : new Socket();
        if (timeout >= 0) {
            socket.setKeepAlive(true);
            socket.setSoTimeout(timeout * 1000);
        }
        socket.connect(address);

        // Get the streams
        OutputStream output = socket.getOutputStream();
        PrintWriter writer = new PrintWriter(output);

        try {
            DataInputStream input = new DataInputStream(socket.getInputStream());
            try {
                for (int j = 0; j < innerLoop; j++) {
                    android.util.Log.d("SSLSocketTest", "GET https://" + host + path + " HTTP/1.1");

                    // Send a request
                    writer.println("GET https://" + host + path + " HTTP/1.1\r");
                    writer.println("Host: " + host + "\r");
                    writer.println("Connection: " + (j == innerLoop - 1 ? "Close" : "Keep-Alive") + "\r");
                    writer.println("\r");
                    writer.flush();

                    int length = -1;
                    boolean chunked = false;

                    String line = input.readLine();

                    if (line == null) {
                        throw new IOException("No response from server");
                        // android.util.Log.d("SSLSocketTest", "No response from server");
                    }

                    // Consume the headers, check content length and encoding type
                    while (line != null && line.length() != 0) {
                        //                    System.out.println(line);
                        int dot = line.indexOf(':');
                        if (dot != -1) {
                            String key = line.substring(0, dot).trim();
                            String value = line.substring(dot + 1).trim();

                            if ("Content-Length".equalsIgnoreCase(key)) {
                                length = Integer.valueOf(value);
                            } else if ("Transfer-Encoding".equalsIgnoreCase(key)) {
                                chunked = "Chunked".equalsIgnoreCase(value);
                            }

                        }
                        line = input.readLine();
                    }

                    assertTrue("Need either content length or chunked encoding", length != -1 || chunked);

                    // Consume the content itself
                    if (chunked) {
                        length = Integer.parseInt(input.readLine(), 16);
                        while (length != 0) {
                            byte[] buffer = new byte[length];
                            input.readFully(buffer);
                            input.readLine();
                            length = Integer.parseInt(input.readLine(), 16);
                        }
                        input.readLine();
                    } else {
                        byte[] buffer = new byte[length];
                        input.readFully(buffer);
                    }

                    // Sleep for the given number of seconds
                    try {
                        Thread.sleep(delay * 1000);
                    } catch (InterruptedException ex) {
                        // Shut up!
                    }
                }
            } finally {
                input.close();
            }
        } finally {
            writer.close();
        }
        // Close the connection
        socket.close();
    }
}

From source file:com.code.android.vibevault.StreamProxy.java

private void processRequest(HttpRequest request, Socket client) throws IllegalStateException, IOException {
    if (request == null) {
        return;/*  w  w w  . ja  va  2s.co  m*/
    }

    String url = request.getRequestLine().getUri();
    HttpResponse realResponse = download(url);
    if (realResponse == null) {
        return;
    }

    InputStream data = realResponse.getEntity().getContent();
    StatusLine line = realResponse.getStatusLine();
    HttpResponse response = new BasicHttpResponse(line);
    response.setHeaders(realResponse.getAllHeaders());

    StringBuilder httpString = new StringBuilder();
    httpString.append(response.getStatusLine().toString());

    httpString.append("\n");
    for (Header h : response.getAllHeaders()) {
        httpString.append(h.getName()).append(": ").append(h.getValue()).append("\n");
    }
    httpString.append("\n");

    try {
        byte[] buffer = httpString.toString().getBytes();
        int readBytes = -1;

        client.getOutputStream().write(buffer, 0, buffer.length);

        // Start streaming content.
        byte[] buff = new byte[1024 * 50];
        while (isRunning && (readBytes = data.read(buff, 0, buff.length)) != -1) {
            client.getOutputStream().write(buff, 0, readBytes);
        }
    } catch (Exception e) {
        Log.e("", e.getMessage(), e);
    } finally {
        if (data != null) {
            data.close();
        }
        client.close();
    }
}