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.mulesoft.agent.monitoring.publisher.ZabbixMonitorPublisher.java

@Override
public boolean flush(@NotNull Collection<List<Metric>> listOfMetrics) {
    Socket zabbixConnection = null;
    OutputStream out = null;//from w  w  w  .  j  av a 2 s  . co m
    BufferedReader in = null;
    try {
        for (List<Metric> metrics : listOfMetrics) {
            for (Metric metric : metrics) {
                zabbixConnection = new Socket(zabbixServer, zabbixPort);

                StringBuilder message = new StringBuilder();
                message.append(MESSAGE_START);
                message.append(host);
                message.append(MESSAGE_MIDDLE_LEFT);
                message.append(metric.getName().replaceAll("\\s", "").replace(":", ""));
                message.append(MESSAGE_MIDDLE_RIGHT);
                message.append(metric.getValue());
                message.append(MESSAGE_END);

                String s = message.toString();

                byte[] chars = s.getBytes();
                int length = chars.length;
                out = zabbixConnection.getOutputStream();
                out.write(new byte[] { 'Z', 'B', 'X', 'D', '\1', (byte) (length & 0xFF),
                        (byte) ((length >> 8) & 0x00FF), (byte) ((length >> 16) & 0x0000FF),
                        (byte) ((length >> 24) & 0x000000FF), '\0', '\0', '\0', '\0' });

                out.write(chars);
                out.flush();

                in = new BufferedReader(new InputStreamReader(zabbixConnection.getInputStream()));
                LOGGER.debug("Message sent to Zabbix: " + message.toString());

            }
        }
    } catch (IOException e) {
        LOGGER.warn("Failed to establish connection to Zabbix", e);
        return false;
    } finally {
        try {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
            if (zabbixConnection != null) {
                zabbixConnection.close();
            }
        } catch (IOException e) {

        }

    }
    return true;
}

From source file:com.dumbster.smtp.SimpleSmtpServer.java

/**
 * Main loop of the SMTP server.//from  w w w  .  j av  a2 s. c om
 */
public void run() {
    stopped = false;
    try {
        try {
            serverSocket = new ServerSocket(port);
            serverSocket.setSoTimeout(TIMEOUT); // Block for maximum of 1.5
            // seconds
        } finally {
            synchronized (this) {
                // Notify when server socket has been created
                notifyAll();
            }
        }

        // Server: loop until stopped
        while (!isStopped()) {
            // Start server socket and listen for client connections
            Socket socket = null;
            try {
                socket = serverSocket.accept();
            } catch (Exception e) {
                if (socket != null) {
                    socket.close();
                }
                continue; // Non-blocking socket timeout occurred: try
                          // accept() again
            }

            // Get the input and output streams
            BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintWriter out = new PrintWriter(socket.getOutputStream());

            synchronized (this) {
                /*
                 * We synchronize over the handle method and the list update
                 * because the client call completes inside the handle
                 * method and we have to prevent the client from reading the
                 * list until we've updated it. For higher concurrency, we
                 * could just change handle to return void and update the
                 * list inside the method to limit the duration that we hold
                 * the lock.
                 */
                List<SmtpMessage> msgs = handleTransaction(out, input);
                saveMessagesInElasticSearch(msgs);
            }
            socket.close();
        }
    } catch (Exception e) {
        logger.error("Smtp Server could not be started", e);
    } finally {
        if (serverSocket != null) {
            try {
                serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.predic8.membrane.core.rules.SSLProxy.java

@Override
public SSLContext getSslInboundContext() {
    return new SSLContext(new SSLParser(), router.getResolverMap(), router.getBaseLocation()) {

        @Override//ww  w. java  2s.c om
        public Socket wrap(Socket socket, byte[] buffer, int position) throws IOException {
            int port = target.getPort();
            if (port == -1)
                port = getPort();

            StreamPump.StreamPumpStats streamPumpStats = router.getStatistics().getStreamPumpStats();
            String protocol = "SSL";

            Connection con = cm.getConnection(target.getHost(), port, connectionConfiguration.getLocalAddr(),
                    null, connectionConfiguration.getTimeout());

            con.out.write(buffer, 0, position);
            con.out.flush();

            String source = socket.getRemoteSocketAddress().toString();
            String dest = con.toString();
            final StreamPump a = new StreamPump(con.in, socket.getOutputStream(), streamPumpStats,
                    protocol + " " + source + " <- " + dest, SSLProxy.this);
            final StreamPump b = new StreamPump(socket.getInputStream(), con.out, streamPumpStats,
                    protocol + " " + source + " -> " + dest, SSLProxy.this);

            socket.setSoTimeout(0);

            String threadName = Thread.currentThread().getName();
            new Thread(a, threadName + " " + protocol + " Backward Thread").start();
            try {
                Thread.currentThread().setName(threadName + " " + protocol + " Onward Thread");
                b.run();
            } finally {
                try {
                    con.close();
                } catch (IOException e) {
                    log.debug("", e);
                }
            }
            throw new SocketException("SSL Forwarding Connection closed.");
        }
    };
}

From source file:com.app.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;/*from   w w w  .  j  av a  2  s  .c  o  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) {
                                    //log.info(key);
                                    bstr = new ByteArrayOutputStream();
                                    object = null;
                                    clientChannel.read(lengthBuffer);
                                    int length = lengthBuffer.getInt(0);
                                    lengthBuffer.clear();
                                    //log.info(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();
                                    //log.info("Message1"+new String(bstr
                                    //      .toByteArray()));
                                    bais = new ByteArrayInputStream(bstr.toByteArray());
                                    ois = new ObjectInputStream(bais); // Offending
                                    // line.
                                    // Produces
                                    // the
                                    // StreamCorruptedException.
                                    //log.info("In read obect");
                                    object = ois.readObject();
                                    //log.info("Class Cast");
                                    //log.info("Class Cast1");
                                    ois.close();
                                    byte[] params = bstr.toByteArray();
                                    bstr.close();
                                    //log.info("readObject");
                                    //log.info("After readObject");
                                    if (object instanceof CloseSocket) {
                                        resultMap.remove(key);
                                        clientChannel.close();
                                        key.cancel();
                                    }
                                    // clientChannel.close();
                                    String serviceurl = (String) object;
                                    String[] serviceRegistry = serviceurl.split("/");
                                    //log.info("classLoaderMap"
                                    //      + urlClassLoaderMap);
                                    //log.info(deployDirectory
                                    //      + "/" + serviceRegistry[0]);

                                    int servicenameIndex;
                                    //log.info(earServicesDirectory
                                    //      + "/" + serviceRegistry[0]
                                    //      + "/" + serviceRegistry[1]);
                                    if (serviceRegistry[0].endsWith(".ear")) {
                                        classLoader = (VFSClassLoader) urlClassLoaderMap.get(deployDirectory
                                                + "/" + serviceRegistry[0] + "/" + serviceRegistry[1]);
                                        servicenameIndex = 2;
                                    } else if (serviceRegistry[0].endsWith(".jar")) {
                                        classLoader = (WebClassLoader) urlClassLoaderMap
                                                .get(deployDirectory + "/" + serviceRegistry[0]);
                                        servicenameIndex = 1;
                                    } else {
                                        classLoader = (WebClassLoader) urlClassLoaderMap
                                                .get(deployDirectory + "/" + serviceRegistry[0]);
                                        servicenameIndex = 1;
                                    }
                                    String serviceName = serviceRegistry[servicenameIndex];
                                    // log.info("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);
                                    // log.info("Key interested Ops");
                                    // continue;
                                }
                                //Thread.sleep(100);
                                /*
                                 * if (classLoader == null) throw new
                                 * Exception(
                                 * "Could able to obtain deployed class loader"
                                 * );
                                 */
                                /*
                                 * log.info(
                                 * "current context classloader" +
                                 * classLoader);
                                 */
                                //log.info("In rad object");
                                bstr = new ByteArrayOutputStream();
                                lengthBuffer.clear();
                                int numberofDataRead = clientChannel.read(lengthBuffer);
                                //log.info("numberofDataRead"
                                //      + numberofDataRead);
                                int length = lengthBuffer.getInt(0);
                                if (length <= 0) {
                                    iterator.remove();
                                    continue;
                                }
                                lengthBuffer.clear();
                                //log.info(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) {
                                    //log.info("bytesRead<length");
                                    iterator.remove();
                                    continue;
                                }
                                //log.info(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");
                                //log.info("Object="
                                //      + object.getClass());
                                // Thread.currentThread().setContextClassLoader(currentContextLoader);
                                if (object instanceof ExecutorParams) {
                                    ExecutorParams exeParams = (ExecutorParams) object;
                                    Object returnValue = null;

                                    //log.info("test socket1");
                                    String ataKey;
                                    ATAConfig ataConfig;
                                    ConcurrentHashMap ataServicesMap;
                                    Enumeration<NodeResourceInfo> noderesourceInfos = addressmap.elements();
                                    NodeResourceInfo noderesourceinfo = null;
                                    String ip = "";
                                    int port = 1000;
                                    long memavailable = 0;
                                    long memcurr = 0;
                                    if (noderesourceInfos.hasMoreElements()) {
                                        noderesourceinfo = noderesourceInfos.nextElement();
                                        if (noderesourceinfo.getMax() != null) {
                                            ip = noderesourceinfo.getHost();
                                            port = Integer.parseInt(noderesourceinfo.getPort());
                                            memavailable = Long.parseLong(noderesourceinfo.getMax())
                                                    - Long.parseLong(noderesourceinfo.getUsed());
                                            ;
                                        }
                                    }

                                    while (noderesourceInfos.hasMoreElements()) {
                                        noderesourceinfo = noderesourceInfos.nextElement();
                                        if (noderesourceinfo.getMax() != null) {
                                            memcurr = Long.parseLong(noderesourceinfo.getMax())
                                                    - Long.parseLong(noderesourceinfo.getUsed());
                                            if (memavailable <= memcurr) {
                                                ip = noderesourceinfo.getHost();
                                                port = Integer.parseInt(noderesourceinfo.getPort());
                                                memavailable = memcurr;
                                            }
                                        }
                                    }
                                    ATAExecutorServiceInfo servicesAvailable;
                                    Socket sock1 = new Socket(ip, port);
                                    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());
                                    //log.info("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);

                                    //   log.info("Written Value="
                                    //         + returnValue.toString());
                                    resultMap.put(key, returnValue);
                                }
                                key.interestOps(SelectionKey.OP_WRITE);
                                //log.info("Key interested Ops1");
                            } else if (key.isWritable()) {
                                // the channel is non blocking so keep it
                                // open
                                // till the
                                // count is >=0
                                //log.info("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
                                //log.info(new String(objData));
                                //while (buffer.hasRemaining())
                                clientChannel.write(buffer); // write
                                resultMap.remove(key);
                                buffer.clear();
                                key.cancel();
                                clientChannel.close();
                                //log.info("In write1");
                                numberOfServicesRequests++;
                                //log.info("Key interested Ops2");
                            }

                        }

                        iterator.remove();
                    } catch (Exception ex) {
                        log.error("Error in executing the executor services thread", ex);
                        //ex.printStackTrace();
                        key.cancel();
                        clientChannel.close();
                        resultMap.remove(key);
                        //ex.printStackTrace();
                    }

                }

            } catch (Exception ex) {
                log.error("Error in executing the executor services thread", ex);
                //ex.printStackTrace();
            }
        }
    } catch (Exception ex) {
        log.error("Error in executing the executor services thread", ex);
    }
}

From source file:net.lightbody.bmp.proxy.jetty.http.handler.ProxyHandler.java

protected HttpTunnel newHttpTunnel(HttpRequest request, HttpResponse response, InetAddress iaddr, int port,
        int timeoutMS) throws IOException {
    try {//from  w ww.j a v  a 2 s.  c o m
        Socket socket = null;
        InputStream in = null;

        String chained_proxy_host = System.getProperty("http.proxyHost");
        if (chained_proxy_host == null) {
            socket = new Socket(iaddr, port);
            socket.setSoTimeout(timeoutMS);
            socket.setTcpNoDelay(true);
        } else {
            int chained_proxy_port = Integer.getInteger("http.proxyPort", 8888).intValue();

            Socket chain_socket = new Socket(chained_proxy_host, chained_proxy_port);
            chain_socket.setSoTimeout(timeoutMS);
            chain_socket.setTcpNoDelay(true);
            if (log.isDebugEnabled())
                log.debug("chain proxy socket=" + chain_socket);

            LineInput line_in = new LineInput(chain_socket.getInputStream());
            byte[] connect = request.toString()
                    .getBytes(net.lightbody.bmp.proxy.jetty.util.StringUtil.__ISO_8859_1);
            chain_socket.getOutputStream().write(connect);

            String chain_response_line = line_in.readLine();
            HttpFields chain_response = new HttpFields();
            chain_response.read(line_in);

            // decode response
            int space0 = chain_response_line.indexOf(' ');
            if (space0 > 0 && space0 + 1 < chain_response_line.length()) {
                int space1 = chain_response_line.indexOf(' ', space0 + 1);

                if (space1 > space0) {
                    int code = Integer.parseInt(chain_response_line.substring(space0 + 1, space1));

                    if (code >= 200 && code < 300) {
                        socket = chain_socket;
                        in = line_in;
                    } else {
                        Enumeration iter = chain_response.getFieldNames();
                        while (iter.hasMoreElements()) {
                            String name = (String) iter.nextElement();
                            if (!_DontProxyHeaders.containsKey(name)) {
                                Enumeration values = chain_response.getValues(name);
                                while (values.hasMoreElements()) {
                                    String value = (String) values.nextElement();
                                    response.setField(name, value);
                                }
                            }
                        }
                        response.sendError(code);
                        if (!chain_socket.isClosed())
                            chain_socket.close();
                    }
                }
            }
        }

        if (socket == null)
            return null;
        HttpTunnel tunnel = new HttpTunnel(socket, in, null);
        return tunnel;
    } catch (IOException e) {
        log.debug(e);
        response.sendError(HttpResponse.__400_Bad_Request);
        return null;
    }
}

From source file:com.github.lindenb.jvarkit.tools.bamviewgui.BamFileRef.java

private void showIgv(final Object chrom, final Object pos) {
    if (igvIP == null || igvPort == null)
        return;//  w  w w.j  a va2  s  .c o m
    Thread thread = new Thread() {
        @Override
        public void run() {
            PrintWriter out = null;
            BufferedReader in = null;
            Socket socket = null;

            try {
                socket = new Socket(igvIP, igvPort);
                out = new PrintWriter(socket.getOutputStream(), true);
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                out.println("goto " + chrom + ":" + pos);
                try {
                    Thread.sleep(5 * 1000);
                } catch (InterruptedException err2) {
                }
            } catch (Exception err) {
                LOG.info("" + err.getMessage());
            } finally {
                if (in != null)
                    try {
                        in.close();
                    } catch (Exception err) {
                    }
                if (out != null)
                    try {
                        out.close();
                    } catch (Exception err) {
                    }
                if (socket != null)
                    try {
                        socket.close();
                    } catch (Exception err) {
                    }
            }
        }
    };
    thread.start();
}

From source file:com.isecpartners.gizmo.HttpRequest.java

void passThroughAllBits() {
    try {//from w  ww .  jav a  2 s .  com
        Socket destinationHost = new Socket(host, port);
        byte[] buf = new byte[1024];
        boolean didNothing = true;
        while (!this.sock.isClosed() && !destinationHost.isClosed()) {
            didNothing = true;
            if (sock.getInputStream().available() > 0) {
                int b = sock.getInputStream().read(buf);
                destinationHost.getOutputStream().write(buf, 0, b);
                didNothing = false;
            }
            if (destinationHost.getInputStream().available() > 0) {
                int b = destinationHost.getInputStream().read(buf);
                sock.getOutputStream().write(buf, 0, b);
                didNothing = false;
            }
            if (didNothing) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException ex) {
                    Logger.getLogger(HttpRequest.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        this.sock.close();
        destinationHost.close();
    } catch (UnknownHostException ex) {
        Logger.getLogger(HttpRequest.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(HttpRequest.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:hornet.framework.clamav.service.ClamAVCheckService.java

/**
 * Cette mthode permet l'envoie d'une commande  ClamAV et retourne le rsultat sous la forme d'une
 * chaine de caractre./*w w  w  .ja  v a  2  s .  c  o  m*/
 *
 * @param command
 *            - la commade  transmettre
 * @param strEndDetection
 *            - la chaine de caractre permettant de dtecter la dernire ligne du retour.
 * @return La rponse de clamAV sans traitement
 * @throws ClamAVException
 *             the clam av exception
 */
private ClamAvResponse callClamAV(final TypeResponse command, final String strEndDetection)
        throws ClamAVException {

    ClamAvResponse result;

    final StringBuilder resultat = new StringBuilder();
    final Date dateDebut = new Date();
    Socket socket = null;
    BufferedReader buffer = null;

    try {
        socket = this.connect(command);
        if (socket == null) {
            result = ClamAvResponse.createNoServiceResponse();
        } else {
            // timeout pour l'ensemble des oprations sur la
            // socket
            socket.setSoTimeout(this.timeout);
            final InputStream input = socket.getInputStream();
            final OutputStream ouput = socket.getOutputStream();

            // envoi de la commande  clamAV
            ouput.write(("n" + command.toString() + "\n").getBytes(UTF_8));

            // Attente et traitement de la rponse
            buffer = new BufferedReader(new InputStreamReader(input, UTF_8));

            String retour = "";
            int indexResultat = -1;
            while (retour != null && indexResultat == -1) {
                retour = buffer.readLine();
                if (retour != null) {
                    indexResultat = retour.indexOf(strEndDetection);
                    resultat.append(retour);
                    resultat.append('\n');
                }
            }
            ClamAVCheckService.LOGGER.debug("Retour ClamAV (en {} ms) :\n{}",
                    new Date().getTime() - dateDebut.getTime(), resultat);
            result = this.traitementReponseClamAV(resultat.toString(), command);
        }
    } catch (final UnknownHostException e) {
        ClamAVCheckService.LOGGER.error(String.format(ERROR_ON_COMMAND, command), e);
        throw new ClamAVException(ERR_TEC_CLAMAV_01, new String[] { e.getMessage() }, e);
    } catch (final IOException e) {
        ClamAVCheckService.LOGGER.error(String.format(ERROR_ON_COMMAND, command), e);
        throw new ClamAVException(ERR_TEC_CLAMAV_01, new String[] { e.getMessage() }, e);
    } finally {
        this.safeClose(command, socket, buffer);
    }

    return result;
}

From source file:marytts.server.RequestHandler.java

/**
 * Constructor to be used for Socket processing (running as a standalone
 * socket server).  <code>inputReader</code> is a Reader reading from from
 * <code>dataSocket.inputStream()</code>. Passing this on is necessary
 * because the mary server does a buffered read on that input stream, and
 * without passing that buffered reader on, data gets lost.
 *///from w  w  w . j  ava2s  .c  o  m
public RequestHandler(Request request, Socket infoSocket, Socket dataSocket, Reader inputReader) {
    if (request == null)
        throw new NullPointerException("Cannot handle null request");
    this.request = request;
    if (infoSocket == null)
        throw new NullPointerException("Received null infoSocket");
    this.infoSocket = infoSocket;
    if (dataSocket == null)
        throw new NullPointerException("Received null dataSocket");
    this.dataSocket = dataSocket;
    this.setName("RH " + request.getId());
    logger = MaryUtils.getLogger(this.getName());
    this.inputReader = new LoggingReader(inputReader, logger);
    clientLogger = MaryUtils.getLogger(this.getName() + " client");
    try {
        clientLogger.addAppender(
                new WriterAppender(new SimpleLayout(), new PrintWriter(infoSocket.getOutputStream(), true)));
        clientLogger.setLevel(Level.WARN);
        // What goes to clientLogger does not go to the normal logfile:
        clientLogger.setAdditivity(false);
    } catch (IOException e) {
        logger.warn("Cannot write warnings to client", e);
    }
}

From source file:net.ostis.sc.memory.impl.remote.rgp.RGPSession.java

public RGPSession(RGPMemory memory, Socket controlSocket, Socket eventSocket)
        throws IOException, RGPProtocolException {
    this.memory = memory;
    this.controlSocket = controlSocket;
    this.eventSocket = eventSocket;
    this.objectsRegistry = new RGPObjectsRegistry(this);
    this.controlStream = new RGPProtocolStream(controlSocket.getInputStream(), controlSocket.getOutputStream(),
            objectsRegistry);//w w  w .ja v  a2 s.  c om
    this.eventStream = new RGPProtocolStream(eventSocket.getInputStream(), eventSocket.getOutputStream(),
            objectsRegistry);

    eventThread = new Thread(this);
    eventThread.setName("RGP Events Listener");
    eventThread.setDaemon(true);
    eventThread.start();

    login();
}