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.liveramp.hank.test.ZkTestCase.java

private static boolean waitForServerUp(int port, long timeout) {
    long start = System.currentTimeMillis();
    while (true) {
        try {//from w w  w.  j a va  2  s .c  o  m
            Socket sock = new Socket("localhost", port);
            BufferedReader reader = null;
            try {
                OutputStream outstream = sock.getOutputStream();
                outstream.write("stat".getBytes());
                outstream.flush();

                Reader isr = new InputStreamReader(sock.getInputStream());
                reader = new BufferedReader(isr);
                String line = reader.readLine();
                if (line != null && line.startsWith("Zookeeper version:")) {
                    return true;
                }
            } finally {
                sock.close();
                if (reader != null) {
                    reader.close();
                }
            }
        } catch (IOException e) {
            // ignore as this is expected
            LOG.info("server localhost:" + port + " not up " + e);
        }

        if (System.currentTimeMillis() > start + timeout) {
            break;
        }
        try {
            Thread.sleep(250);
        } catch (InterruptedException e) {
            // ignore
        }
    }
    return false;
}

From source file:org.alfresco.webservice.util.ContentUtils.java

/**
 * Streams content into the repository.  Once done a content details string is returned and this can be used to update 
 * a content property in a CML statement.
 * /*from www  . jav  a  2s.c om*/
 * @param file  the file to stream into the repository
 * @param host  the host name of the destination repository
 * @param port  the port name of the destination repository
 * @param webAppName        the name of the target web application (default 'alfresco')
 * @param mimetype the mimetype of the file, ignored if null
 * @param encoding the encoding of the file, ignored if null
 * @return      the content data that can be used to set the content property in a CML statement  
 */
@SuppressWarnings("deprecation")
public static String putContent(File file, String host, int port, String webAppName, String mimetype,
        String encoding) {
    String result = null;

    try {
        String url = "/" + webAppName + "/upload/" + URLEncoder.encode(file.getName(), "UTF-8") + "?ticket="
                + AuthenticationUtils.getTicket();
        if (mimetype != null) {
            url = url + "&mimetype=" + mimetype;
        }
        if (encoding != null) {
            url += "&encoding=" + encoding;
        }

        String request = "PUT " + url + " HTTP/1.1\n" + "Cookie: JSESSIONID="
                + AuthenticationUtils.getAuthenticationDetails().getSessionId() + ";\n" + "Content-Length: "
                + file.length() + "\n" + "Host: " + host + ":" + port + "\n" + "Connection: Keep-Alive\n"
                + "\n";

        // Open sockets and streams
        Socket socket = new Socket(host, port);
        DataOutputStream os = new DataOutputStream(socket.getOutputStream());
        DataInputStream is = new DataInputStream(socket.getInputStream());

        try {
            if (socket != null && os != null && is != null) {
                // Write the request header
                os.writeBytes(request);

                // Stream the content onto the server
                InputStream fileInputStream = new FileInputStream(file);
                int byteCount = 0;
                byte[] buffer = new byte[BUFFER_SIZE];
                int bytesRead = -1;
                while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                    os.write(buffer, 0, bytesRead);
                    byteCount += bytesRead;
                }
                os.flush();
                fileInputStream.close();

                // Read the response and deal with any errors that might occur
                boolean firstLine = true;
                String responseLine;
                while ((responseLine = is.readLine()) != null) {
                    if (firstLine == true) {
                        if (responseLine.contains("200") == true) {
                            firstLine = false;
                        } else if (responseLine.contains("401") == true) {
                            throw new RuntimeException(
                                    "Content could not be uploaded because invalid credentials have been supplied.");
                        } else if (responseLine.contains("403") == true) {
                            throw new RuntimeException(
                                    "Content could not be uploaded because user does not have sufficient privileges.");
                        } else {
                            throw new RuntimeException(
                                    "Error returned from upload servlet (" + responseLine + ")");
                        }
                    } else if (responseLine.contains("contentUrl") == true) {
                        result = responseLine;
                        break;
                    }
                }
            }
        } finally {
            try {
                // Close the streams and socket
                if (os != null) {
                    os.close();
                }
                if (is != null) {
                    is.close();
                }
                if (socket != null) {
                    socket.close();
                }
            } catch (Exception e) {
                throw new RuntimeException("Error closing sockets and streams", e);
            }
        }
    } catch (Exception e) {
        throw new RuntimeException("Error writing content to repository server", e);
    }

    return result;
}

From source file:com.yahoo.pulsar.zookeeper.LocalBookkeeperEnsemble.java

public static boolean waitForServerUp(String hp, long timeout) {
    long start = MathUtils.now();
    String split[] = hp.split(":");
    String host = split[0];/*from   w ww .  java  2  s . c  om*/
    int port = Integer.parseInt(split[1]);
    while (true) {
        try {
            Socket sock = new Socket(host, port);
            BufferedReader reader = null;
            try {
                OutputStream outstream = sock.getOutputStream();
                outstream.write("stat".getBytes());
                outstream.flush();

                reader = new BufferedReader(new InputStreamReader(sock.getInputStream()));
                String line = reader.readLine();
                if (line != null && line.startsWith("Zookeeper version:")) {
                    LOG.info("Server UP");
                    return true;
                }
            } finally {
                sock.close();
                if (reader != null) {
                    reader.close();
                }
            }
        } catch (IOException e) {
            // ignore as this is expected
            LOG.info("server " + hp + " not up " + e);
        }

        if (MathUtils.now() > start + timeout) {
            break;
        }
        try {
            Thread.sleep(250);
        } catch (InterruptedException e) {
            // ignore
        }
    }
    return false;
}

From source file:gridool.util.xfer.TransferUtils.java

public static void send(@Nonnull final FastByteArrayOutputStream data, @Nonnull final String fileName,
        @Nullable final String writeDirPath, @Nonnull final InetAddress dstAddr, final int dstPort,
        final boolean append, final boolean sync, @Nullable final TransferClientHandler handler)
        throws IOException {
    final SocketAddress dstSockAddr = new InetSocketAddress(dstAddr, dstPort);
    SocketChannel channel = null;
    Socket socket = null;
    final OutputStream out;
    try {/*from w  w w .j  a  v a 2s .c  o  m*/
        channel = SocketChannel.open();
        socket = channel.socket();
        socket.connect(dstSockAddr);
        out = socket.getOutputStream();
    } catch (IOException e) {
        LOG.error("failed to connect: " + dstSockAddr, e);
        IOUtils.closeQuietly(channel);
        NetUtils.closeQuietly(socket);
        throw e;
    }

    DataInputStream din = null;
    if (sync) {
        InputStream in = socket.getInputStream();
        din = new DataInputStream(in);
    }
    final DataOutputStream dos = new DataOutputStream(out);
    final StopWatch sw = new StopWatch();
    try {
        IOUtils.writeString(fileName, dos);
        IOUtils.writeString(writeDirPath, dos);
        long nbytes = data.size();
        dos.writeLong(nbytes);
        dos.writeBoolean(append);
        dos.writeBoolean(sync);
        if (handler == null) {
            dos.writeBoolean(false);
        } else {
            dos.writeBoolean(true);
            handler.writeAdditionalHeader(dos);
        }

        // send file using zero-copy send
        data.writeTo(out);

        if (LOG.isDebugEnabled()) {
            LOG.debug("Sent a file data '" + fileName + "' of " + nbytes + " bytes to " + dstSockAddr.toString()
                    + " in " + sw.toString());
        }

        if (sync) {// receive ack in sync mode
            long remoteRecieved = din.readLong();
            if (remoteRecieved != nbytes) {
                throw new IllegalStateException(
                        "Sent " + nbytes + " bytes, but remote node received " + remoteRecieved + " bytes");
            }
        }
    } catch (FileNotFoundException e) {
        LOG.error(PrintUtils.prettyPrintStackTrace(e, -1));
        throw e;
    } catch (IOException e) {
        LOG.error(PrintUtils.prettyPrintStackTrace(e, -1));
        throw e;
    } finally {
        IOUtils.closeQuietly(din, dos);
        IOUtils.closeQuietly(channel);
        NetUtils.closeQuietly(socket);
    }
}

From source file:gridool.util.xfer.TransferUtils.java

public static void sendfile(@Nonnull final File file, final long fromPos, final long count,
        @Nullable final String writeDirPath, @Nonnull final InetAddress dstAddr, final int dstPort,
        final boolean append, final boolean sync, @Nonnull final TransferClientHandler handler)
        throws IOException {
    if (!file.exists()) {
        throw new IllegalArgumentException(file.getAbsolutePath() + " does not exist");
    }//from   w ww . jav a 2s .  c om
    if (!file.isFile()) {
        throw new IllegalArgumentException(file.getAbsolutePath() + " is not file");
    }
    if (!file.canRead()) {
        throw new IllegalArgumentException(file.getAbsolutePath() + " cannot read");
    }

    final SocketAddress dstSockAddr = new InetSocketAddress(dstAddr, dstPort);
    SocketChannel channel = null;
    Socket socket = null;
    final OutputStream out;
    try {
        channel = SocketChannel.open();
        socket = channel.socket();
        socket.connect(dstSockAddr);
        out = socket.getOutputStream();
    } catch (IOException e) {
        LOG.error("failed to connect: " + dstSockAddr, e);
        IOUtils.closeQuietly(channel);
        NetUtils.closeQuietly(socket);
        throw e;
    }

    DataInputStream din = null;
    if (sync) {
        InputStream in = socket.getInputStream();
        din = new DataInputStream(in);
    }
    final DataOutputStream dos = new DataOutputStream(out);
    final StopWatch sw = new StopWatch();
    FileInputStream src = null;
    final long nbytes;
    try {
        src = new FileInputStream(file);
        FileChannel fc = src.getChannel();

        String fileName = file.getName();
        IOUtils.writeString(fileName, dos);
        IOUtils.writeString(writeDirPath, dos);
        long xferBytes = (count == -1L) ? fc.size() : count;
        dos.writeLong(xferBytes);
        dos.writeBoolean(append); // append=false
        dos.writeBoolean(sync);
        if (handler == null) {
            dos.writeBoolean(false);
        } else {
            dos.writeBoolean(true);
            handler.writeAdditionalHeader(dos);
        }

        // send file using zero-copy send
        nbytes = fc.transferTo(fromPos, xferBytes, channel);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Sent a file '" + file.getAbsolutePath() + "' of " + nbytes + " bytes to "
                    + dstSockAddr.toString() + " in " + sw.toString());
        }

        if (sync) {// receive ack in sync mode
            long remoteRecieved = din.readLong();
            if (remoteRecieved != xferBytes) {
                throw new IllegalStateException(
                        "Sent " + xferBytes + " bytes, but remote node received " + remoteRecieved + " bytes");
            }
        }

    } catch (FileNotFoundException e) {
        LOG.error(PrintUtils.prettyPrintStackTrace(e, -1));
        throw e;
    } catch (IOException e) {
        LOG.error(PrintUtils.prettyPrintStackTrace(e, -1));
        throw e;
    } finally {
        IOUtils.closeQuietly(src);
        IOUtils.closeQuietly(din, dos);
        IOUtils.closeQuietly(channel);
        NetUtils.closeQuietly(socket);
    }
}

From source file:com.linkedin.d2.quorum.ZKPeer.java

/**
 * Send the 4letterword/* ww w.  j a  v a2  s  .  co m*/
 *
 * @param host- destination host
 * @param port- destination port
 * @param cmd- the 4letterword (stat, srvr,etc. - see
 *          http://zookeeper.apache.org/doc/r3.3.3/zookeeperAdmin.html#sc_zkCommands)
 * @return
 * @throws IOException
 */
public static String sendCommand(String host, int port, String cmd) throws IOException {
    // NOTE: ignore CancelledKeyException in logs caused by
    // https://issues.apache.org/jira/browse/ZOOKEEPER-1237
    Socket sock = new Socket(host, port);
    BufferedReader reader = null;
    try {
        OutputStream outstream = sock.getOutputStream();
        outstream.write(cmd.getBytes());
        outstream.flush();
        sock.shutdownOutput();

        reader = new BufferedReader(new InputStreamReader(sock.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        return sb.toString();
    } finally {
        sock.close();
        if (reader != null) {
            reader.close();
        }
    }
}

From source file:cit360.sandbox.BackEndMenu.java

public static final void smtpExample() {
    // declaration section:
    // smtpClient: our client socket
    // os: output stream
    // is: input stream
    Socket smtpSocket = null;
    DataOutputStream os = null;/*from   ww w. ja  v a  2s  . co m*/
    DataInputStream is = null;
    // Initialization section:
    // Try to open a socket on port 25
    // Try to open input and output streams
    try {
        smtpSocket = new Socket("localhost", 25);
        os = new DataOutputStream(smtpSocket.getOutputStream());
        is = new DataInputStream(smtpSocket.getInputStream());
    } catch (UnknownHostException e) {
        System.err.println("Did not recognize server: localhost");
    } catch (IOException e) {
        System.err.println("Was not able to open I/O connection to: localhost");
    }
    // If everything has been initialized then we want to write some data
    // to the socket we have opened a connection to on port 25
    if (smtpSocket != null && os != null && is != null) {
        try {

            os.writeBytes("HELO\n");
            os.writeBytes("MAIL From: david.banks0889@gmail.com\n");
            os.writeBytes("RCPT To: david.banks0889@gmail.com\n");
            os.writeBytes("DATA\n");
            os.writeBytes("From: david.banks0889@gmail.com\n");
            os.writeBytes("Subject: TEST\n");
            os.writeBytes("Hi there\n"); // message body
            os.writeBytes("\n.\n");
            os.writeBytes("QUIT");
            // keep on reading from/to the socket till we receive the "Ok" from SMTP,
            // once we received that then we want to break.
            String responseLine;
            while ((responseLine = is.readLine()) != null) {
                System.out.println("Server: " + responseLine);
                if (responseLine.contains("Ok")) {
                    break;
                }
            }
            // clean up:
            // close the output stream
            // close the input stream
            // close the socket
            os.close();
            is.close();
            smtpSocket.close();
        } catch (UnknownHostException e) {
            System.err.println("Trying to connect to unknown host: " + e);
        } catch (IOException e) {
            System.err.println("IOException:  " + e);
        }
    }
}

From source file:Messenger.TorLib.java

/**
 *  This method Creates a socket, then sends the inital SOCKS request info
 *  It stops before reading so that other methods may
 *  differently interpret the results.  It returns the open socket.
 *
 * @param targetHostname The hostname of the destination host.
 * @param targetPort The port to connect to
 * @param req SOCKS/TOR request code//from w  w  w  .j  av a 2  s.  c om
 * @return An open Socket that has been sent the SOCK4a init codes.
 * @throws IOException from any Socket problems
 */
static Socket TorSocketPre(String targetHostname, int targetPort, byte req) throws IOException {

    Socket s;
    //      System.out.println("Opening connection to "+targetHostname+":"+targetPort+
    //            " via proxy "+proxyAddr+":"+proxyPort+" of type "+req);
    s = new Socket(proxyAddr, proxyPort);
    DataOutputStream os = new DataOutputStream(s.getOutputStream());
    os.writeByte(SOCKS_VERSION);
    os.writeByte(req);
    // 2 bytes
    os.writeShort(targetPort);
    // 4 bytes, high byte first
    os.writeInt(SOCKS4A_FAKEIP);
    os.writeByte(SOCKS_DELIM);
    os.writeBytes(targetHostname);
    os.writeByte(SOCKS_DELIM);
    return (s);
}

From source file:EZShare.SubscribeCommandConnection.java

public static void establishPersistentConnection(Boolean secure, int port, String ip, int id,
        JSONObject unsubscribJsonObject, String commandname, String name, String owner, String description,
        String channel, String uri, List<String> tags, String ezserver, String secret, Boolean relay,
        String servers) throws URISyntaxException {
    //secure = false;
    try {// www  . ja va  2  s  .c  o  m
        System.out.print(port + ip);
        Socket socket = null;
        if (secure) {

            SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
            socket = (SSLSocket) sslsocketfactory.createSocket(ip, port);
        } else {
            socket = new Socket(ip, port);
        }
        BufferedReader Reader = new BufferedReader(new InputStreamReader(System.in));
        DataOutputStream output = new DataOutputStream(socket.getOutputStream());
        DataInputStream input = new DataInputStream(socket.getInputStream());

        JSONObject command = new JSONObject();
        Resource resource = new Resource();
        command = resource.inputToJSON(commandname, id, name, owner, description, channel, uri, tags, ezserver,
                secret, relay, servers);

        output.writeUTF(command.toJSONString());
        Client.debug("SEND", command.toJSONString());
        //output.writeUTF(command.toJSONString());
        new Thread(new Runnable() {
            @Override
            public void run() {
                String string = null;
                try {
                    while (true/*(string = input.readUTF()) != null*/) {
                        String serverResponse = input.readUTF();
                        JSONParser parser = new JSONParser();
                        JSONObject response = (JSONObject) parser.parse(serverResponse);
                        Client.debug("RECEIVE", response.toJSONString());
                        //System.out.println(serverResponse);          
                        //                     if((string = Reader.readLine()) != null){
                        //                        if(onKeyPressed(output,string,unsubscribJsonObject)) break;
                        //                     }
                        if (flag == 1) {
                            break;
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (ParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                String string = null;
                try {
                    while ((string = Reader.readLine()) != null) {
                        flag = 1;
                        if (onKeyPressed(output, string, unsubscribJsonObject))
                            break;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:expect4j.ExpectUtils.java

/**
 * Creates an HTTP client connection to a specified HTTP server and
 * returns the entire response.  This function simulates <code>curl
 * http://remotehost/url</code>./*  w w w  .  j  a v  a 2s  .  co m*/
 *
 * @param remotehost the DNS or IP address of the HTTP server
 * @param url the path/file of the resource to look up on the HTTP
 *        server
 * @return the response from the HTTP server
 * @throws Exception upon a variety of error conditions
 */
public static String Http(String remotehost, String url) throws Exception {
    Socket s = null;
    s = new Socket(remotehost, 80);
    logger.debug("Connected to " + s.getInetAddress().toString());

    if (false) {
        // for serious connection-oriented debugging only
        PrintWriter out = new PrintWriter(s.getOutputStream(), false);
        BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));

        System.out.println("Sending request");
        out.print("GET " + url + " HTTP/1.1\r\n");
        out.print("Host: " + remotehost + "\r\n");
        out.print("Connection: close\r\n");
        out.print("User-Agent: Expect4j\r\n");
        out.print("\r\n");
        out.flush();
        System.out.println("Request sent");

        System.out.println("Receiving response");
        String line;
        while ((line = in.readLine()) != null)
            System.out.println(line);
        System.out.println("Received response");
        if (line == null)
            System.exit(0);
    }

    Expect4j expect = new Expect4j(s);

    logger.debug("Sending HTTP request for " + url);
    expect.send("GET " + url + " HTTP/1.1\r\n");
    expect.send("Host: " + remotehost + "\r\n");
    expect.send("Connection: close\r\n");
    expect.send("User-Agent: Expect4j\r\n");
    expect.send("\r\n");

    logger.debug("Waiting for HTTP response");
    String remaining = null;
    expect.expect(new Match[] { new RegExpMatch("HTTP/1.[01] \\d{3} (.*)\n?\r", new Closure() {
        public void run(ExpectState state) {
            logger.trace("Detected HTTP Response Header");

            // save http code
            String match = state.getMatch();
            String parts[] = match.split(" ");

            state.addVar("httpCode", parts[1]);
            state.exp_continue();
        }
    }), new RegExpMatch("Content-Type: (.*\\/.*)\r\n", new Closure() {
        public void run(ExpectState state) {
            logger.trace("Detected Content-Type header");
            state.addVar("contentType", state.getMatch());
            state.exp_continue();
        }
    }), new EofMatch(new Closure() { // should cause entire page to be collected
        public void run(ExpectState state) {
            logger.trace("Found EOF, done receiving HTTP response");
        }
    }), // Will cause buffer to be filled up till end
            new TimeoutMatch(10000, new Closure() {
                public void run(ExpectState state) {
                    logger.trace("Timeout waiting for HTTP response");
                }
            }) });

    remaining = expect.getLastState().getBuffer(); // from EOF matching

    String httpCode = (String) expect.getLastState().getVar("httpCode");

    String contentType = (String) expect.getLastState().getVar("contentType");

    s.close();

    return remaining;
}