Example usage for java.net Socket getInputStream

List of usage examples for java.net Socket getInputStream

Introduction

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

Prototype

public InputStream getInputStream() throws IOException 

Source Link

Document

Returns an input stream for this socket.

Usage

From source file:Messenger.TorLib.java

/**
 * This method opens a TOR socket, and does an anonymous DNS resolve through it.
 * Since Tor caches things, this is a very fast lookup if we've already connected there
 * The resolve does a gethostbyname() on the exit node.
 * @param targetHostname String containing the hostname to look up.
 * @return String representation of the IP address: "x.x.x.x"
 */// w w  w  . jav  a 2s. com
static String TorResolve(String targetHostname) {
    int targetPort = 0; // we dont need a port to resolve

    try {
        Socket s = TorSocketPre(targetHostname, targetPort, TOR_RESOLVE);
        DataInputStream is = new DataInputStream(s.getInputStream());

        byte version = is.readByte();
        byte status = is.readByte();
        if (status != (byte) 90) {
            //failed for some reason, return useful exception
            throw (new IOException(ParseSOCKSStatus(status)));
        }
        int port = is.readShort();
        byte[] ipAddrBytes = new byte[4];
        is.read(ipAddrBytes);
        InetAddress ia = InetAddress.getByAddress(ipAddrBytes);
        //System.out.println("Resolved into:"+ia);
        is.close();
        String addr = ia.toString().substring(1); // clip off the "/"
        return (addr);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return (null);
}

From source file:com.comcast.viper.flume2storm.zookeeper.ZkTestUtils.java

/**
 * Utility function to send a command to the internal server. ZK servers
 * accepts 4 byte command strings to test their liveness.
 *///from   w ww  .  java 2s. co m
protected static String send4LetterWord(final String host, final int port, final String cmd) {
    Preconditions.checkArgument(cmd.length() == 4);
    try {
        final Socket sock = new Socket(host, port);
        OutputStream outstream = null;
        BufferedReader reader = null;
        try {
            outstream = sock.getOutputStream();
            outstream.write(cmd.getBytes());
            outstream.flush();

            reader = new BufferedReader(new InputStreamReader(sock.getInputStream()));
            final StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            return sb.toString();
        } finally {
            if (outstream != null) {
                outstream.close();
            }
            sock.close();
            if (reader != null) {
                reader.close();
            }
        }
    } catch (final Exception e) {
        System.out.println(e.getMessage());
        return StringUtils.EMPTY;
    }
}

From source file:info.bonjean.quinkana.Main.java

private static void run(String[] args) throws QuinkanaException {
    Properties properties = new Properties();
    InputStream inputstream = Main.class.getResourceAsStream("/config.properties");

    try {//from w ww.  j a  v  a  2 s  .c o m
        properties.load(inputstream);
        inputstream.close();
    } catch (IOException e) {
        throw new QuinkanaException("cannot load internal properties", e);
    }

    String name = (String) properties.get("name");
    String description = (String) properties.get("description");
    String url = (String) properties.get("url");
    String version = (String) properties.get("version");
    String usage = (String) properties.get("help.usage");
    String defaultHost = (String) properties.get("default.host");
    int defaultPort = Integer.valueOf(properties.getProperty("default.port"));

    ArgumentParser parser = ArgumentParsers.newArgumentParser(name).description(description)
            .epilog("For more information, go to " + url).version("${prog} " + version).usage(usage);
    parser.addArgument("ACTION").type(Action.class).choices(Action.tail, Action.list).dest("action");
    parser.addArgument("-H", "--host").setDefault(defaultHost)
            .help(String.format("logstash host (default: %s)", defaultHost));
    parser.addArgument("-P", "--port").type(Integer.class).setDefault(defaultPort)
            .help(String.format("logstash TCP port (default: %d)", defaultPort));
    parser.addArgument("-f", "--fields").nargs("+").help("fields to display");
    parser.addArgument("-i", "--include").nargs("+").help("include filter (OR), example host=example.com")
            .metavar("FILTER").type(Filter.class);
    parser.addArgument("-x", "--exclude").nargs("+")
            .help("exclude filter (OR, applied after include), example: severity=debug").metavar("FILTER")
            .type(Filter.class);
    parser.addArgument("-s", "--single").action(Arguments.storeTrue()).help("display single result and exit");
    parser.addArgument("--version").action(Arguments.version()).help("output version information and exit");

    Namespace ns = parser.parseArgsOrFail(args);

    Action action = ns.get("action");
    List<String> fields = ns.getList("fields");
    List<Filter> includes = ns.getList("include");
    List<Filter> excludes = ns.getList("exclude");
    boolean single = ns.getBoolean("single");
    String host = ns.getString("host");
    int port = ns.getInt("port");

    final Socket clientSocket;
    final InputStream is;
    try {
        clientSocket = new Socket(host, port);
        is = clientSocket.getInputStream();
    } catch (IOException e) {
        throw new QuinkanaException("cannot connect to the server " + host + ":" + port, e);
    }

    // add a hook to ensure we clean the resources when leaving
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });

    // prepare JSON parser
    ObjectMapper mapper = new ObjectMapper();
    JsonFactory jsonFactory = mapper.getFactory();
    JsonParser jp;
    try {
        jp = jsonFactory.createParser(is);
    } catch (IOException e) {
        throw new QuinkanaException("error during JSON parser creation", e);
    }

    JsonToken token;

    // action=list
    if (action.equals(Action.list)) {
        try {
            // do this in a separate loop to not pollute the main loop
            while ((token = jp.nextToken()) != null) {
                if (token != JsonToken.START_OBJECT)
                    continue;

                // parse object
                JsonNode node = jp.readValueAsTree();

                // print fields
                Iterator<String> fieldNames = node.fieldNames();
                while (fieldNames.hasNext())
                    System.out.println(fieldNames.next());

                System.exit(0);
            }
        } catch (IOException e) {
            throw new QuinkanaException("error during JSON parsing", e);
        }
    }

    // action=tail
    try {
        while ((token = jp.nextToken()) != null) {
            if (token != JsonToken.START_OBJECT)
                continue;

            // parse object
            JsonNode node = jp.readValueAsTree();

            // filtering (includes)
            if (includes != null) {
                boolean skip = true;
                for (Filter include : includes) {
                    if (include.match(node)) {
                        skip = false;
                        break;
                    }
                }
                if (skip)
                    continue;
            }

            // filtering (excludes)
            if (excludes != null) {
                boolean skip = false;
                for (Filter exclude : excludes) {
                    if (exclude.match(node)) {
                        skip = true;
                        break;
                    }
                }
                if (skip)
                    continue;
            }

            // if no field specified, print raw output (JSON)
            if (fields == null) {
                System.out.println(node.toString());
                if (single)
                    break;
                continue;
            }

            // formatted output, build and print the string
            StringBuilder sb = new StringBuilder(128);
            for (String field : fields) {
                if (sb.length() > 0)
                    sb.append(" ");

                if (node.get(field) != null && node.get(field).textValue() != null)
                    sb.append(node.get(field).textValue());
            }
            System.out.println(sb.toString());

            if (single)
                break;
        }
    } catch (IOException e) {
        throw new QuinkanaException("error during JSON parsing", e);
    }
}

From source file:net.arccotangent.pacchat.net.Client.java

public static void sendMessage(String msg, String ip_address) {
    client_log.i("Sending message to " + ip_address);
    client_log.i("Connecting to server...");

    PublicKey pub;//from   ww w . j a  v a 2  s.co  m
    PrivateKey priv;
    Socket socket;
    BufferedReader input;
    BufferedWriter output;

    client_log.i("Checking for recipient's public key...");
    if (KeyManager.checkIfIPKeyExists(ip_address)) {
        client_log.i("Public key found.");
    } else {
        client_log.i("Public key not found, requesting key from their server.");
        try {
            Socket socketGetkey = new Socket();
            socketGetkey.connect(new InetSocketAddress(InetAddress.getByName(ip_address), Server.PORT), 1000);
            BufferedReader inputGetkey = new BufferedReader(
                    new InputStreamReader(socketGetkey.getInputStream()));
            BufferedWriter outputGetkey = new BufferedWriter(
                    new OutputStreamWriter(socketGetkey.getOutputStream()));

            outputGetkey.write("301 getkey");
            outputGetkey.newLine();
            outputGetkey.flush();

            String pubkeyB64 = inputGetkey.readLine();
            byte[] pubEncoded = Base64.decodeBase64(pubkeyB64);
            X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubEncoded);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");

            outputGetkey.close();
            inputGetkey.close();

            KeyManager.saveKeyByIP(ip_address, keyFactory.generatePublic(pubSpec));
        } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException e) {
            client_log.e("Error saving recipient's key!");
            e.printStackTrace();
        }
    }

    try {
        socket = new Socket();
        socket.connect(new InetSocketAddress(InetAddress.getByName(ip_address), Server.PORT), 1000);
        input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        output = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
    } catch (SocketTimeoutException e) {
        client_log.e("Connection to server timed out!");
        e.printStackTrace();
        return;
    } catch (ConnectException e) {
        client_log.e("Connection to server was refused!");
        e.printStackTrace();
        return;
    } catch (UnknownHostException e) {
        client_log.e("You entered an invalid IP address!");
        e.printStackTrace();
        return;
    } catch (IOException e) {
        client_log.e("Error connecting to server!");
        e.printStackTrace();
        return;
    }

    try {
        Thread.sleep(100);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    pub = KeyManager.loadKeyByIP(ip_address);
    priv = Main.getKeypair().getPrivate();

    String cryptedMsg = MsgCrypto.encryptAndSignMessage(msg, pub, priv);
    try {
        client_log.i("Sending message to recipient.");
        output.write("200 encrypted message");
        output.newLine();
        output.write(cryptedMsg);
        output.newLine();
        output.flush();

        String ack = input.readLine();
        switch (ack) {
        case "201 message acknowledgement":
            client_log.i("Transmission successful, received server acknowledgement.");
            break;
        case "202 unable to decrypt":
            client_log.e(
                    "Transmission failure! Server reports that the message could not be decrypted. Did your keys change? Asking recipient for key update.");
            kuc_id++;
            KeyUpdateClient kuc = new KeyUpdateClient(kuc_id, ip_address);
            kuc.start();
            break;
        case "203 unable to verify":
            client_log.w("**********************************************");
            client_log.w(
                    "Transmission successful, but the receiving server reports that the authenticity of the message could not be verified!");
            client_log.w(
                    "Someone may be tampering with your connection! This is an unlikely, but not impossible scenario!");
            client_log.w(
                    "If you are sure the connection was not tampered with, consider requesting a key update.");
            client_log.w("**********************************************");
            break;
        case "400 invalid transmission header":
            client_log.e(
                    "Transmission failure! Server reports that the message is invalid. Try updating your software and have the recipient do the same. If this does not fix the problem, report the error to developers.");
            break;
        default:
            client_log.w("Server responded with unexpected code: " + ack);
            client_log.w("Transmission might not have been successful.");
            break;
        }

        output.close();
        input.close();
    } catch (IOException e) {
        client_log.e("Error sending message to recipient!");
        e.printStackTrace();
    }
}

From source file:gridool.communication.transport.tcp.GridMasterSlaveWorkerServer.java

static boolean handleConnection(final Socket clientSocket, final GridTransportListener listener,
        final ExecutorService msgProcPool) {
    final InputStream is;
    final int size;
    try {//from   ww w. j ava  2s .c  o  m
        is = clientSocket.getInputStream();
        if (LOG.isDebugEnabled()) {
            final int available = is.available();
            if (available == 0) {
                LOG.debug("Reading data from socket [" + clientSocket + "] seems to be blocked");
            }
        }
        size = IOUtils.readUnsignedIntOrEOF(is);
    } catch (IOException e) {
        LOG.fatal(PrintUtils.prettyPrintStackTrace(e, -1));
        return false;
    }
    if (size == -1) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Connection is closed by remote peer: " + clientSocket);
        }
        return false;
    } else if (size <= 0) {
        LOG.warn("Illegal message (size: " + size + ") was detected for a connection: " + clientSocket);
        return false;
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Start reading " + size + " bytes from a socket [" + clientSocket + ']');
    }
    // read an object from stream
    final byte[] b = new byte[size];
    try {
        IOUtils.readFully(is, b, 0, size);
    } catch (IOException ioe) {
        LOG.fatal("Failed to read data from " + clientSocket, ioe);
        return false;
    }
    msgProcPool.execute(new Runnable() {
        public void run() {
            processRequest(b, listener, clientSocket);
        }
    });
    return true;
}

From source file:com.stratuscom.harvester.codebase.ClassServer.java

/**
 * Read the request/response and return the initial line.
 *///from w w  w .j ava 2  s .  c  om
private static String getInput(Socket sock, boolean isRequest) throws IOException {
    BufferedInputStream in = new BufferedInputStream(sock.getInputStream(), 256);
    StringBuffer buf = new StringBuffer(80);
    do {
        if (!readLine(in, buf)) {
            return null;
        }
    } while (isRequest && buf.length() == 0);
    String initial = buf.toString();
    do {
        buf.setLength(0);
    } while (readLine(in, buf) && buf.length() > 0);
    return initial;
}

From source file:no.antares.clutil.hitman.MessageChannel.java

/** Send message to HitMan, @return response */
public static String send(String host, int port, String message) throws IOException {
    Socket kkSocket = null;
    PrintWriter out = null;//from   w  ww  .  java 2 s. c o m
    BufferedReader in = null;
    try {
        kkSocket = new Socket(host, port);
        out = new PrintWriter(kkSocket.getOutputStream(), true);
        out.println(message);

        if (StringUtils.isBlank(reply2(message)))
            return "";

        in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream()));
        StringBuffer reply = new StringBuffer();
        String fromServer;
        while ((fromServer = in.readLine()) != null) {
            logger.trace("received: " + fromServer);
            reply.append(fromServer);
        }
        return reply.toString();
    } catch (ConnectException e) {
        logger.warn("send(" + message + ") could not connect to: " + host + ":" + port);
        throw e;
    } catch (IOException e) {
        logger.warn("send(" + message + ") could not send to: " + host + ":" + port);
        throw e;
    } finally {
        close(out);
        close(in);
        close(kkSocket);
    }
}

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  w w w.java  2  s .  co  m*/
 * @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.barchart.udt.AppServer.java

private static void copyFile(final Socket sock) {
    log.info("Inside copy file ");
    final Runnable runner = new Runnable() {
        public void run() {
            InputStream is = null;
            OutputStream os = null;
            try {
                is = sock.getInputStream();
                final byte[] bytes = new byte[1024];
                final int bytesRead = is.read(bytes);
                final String str = new String(bytes);
                if (str.startsWith("GET ")) {
                    int nameIndex = 0;
                    for (final byte b : bytes) {
                        if (b == '\n') {
                            break;
                        }//  w w w. j  a  va  2 s .  com
                        nameIndex++;
                    }
                    // Eat the \n.
                    nameIndex++;
                    final String fileName = new String(bytes, 4, nameIndex).trim();
                    log.info("File name: " + fileName);
                    final File f = new File(fileName);
                    final FileInputStream fis = new FileInputStream(f);
                    os = sock.getOutputStream();

                    copy(fis, os, f.length());
                    os.close();
                    return;
                }
                int nameIndex = 0;
                int lengthIndex = 0;
                boolean foundFirst = false;
                //boolean foundSecond = false;
                for (final byte b : bytes) {
                    if (!foundFirst) {
                        nameIndex++;
                    }
                    lengthIndex++;
                    if (b == '\n') {
                        if (foundFirst) {
                            break;
                        }
                        foundFirst = true;
                    }
                }
                if (nameIndex < 2) {
                    // First bytes was a LF?
                    sock.close();
                    return;
                }
                String dataString = new String(bytes);
                int fileLengthIndex = dataString.indexOf("\n", nameIndex + 1);
                final String fileName = new String(bytes, 0, nameIndex).trim();
                final String lengthString = dataString.substring(nameIndex, fileLengthIndex);
                log.info("lengthString " + lengthString);
                final long length = Long.parseLong(lengthString);
                final File file = new File(fileName);
                os = new FileOutputStream(file);
                final int len = bytesRead - lengthIndex;
                if (len > 0) {
                    os.write(bytes, lengthIndex, len);
                }
                start = System.currentTimeMillis();
                copy(is, os, length);
            } catch (final IOException e) {
                log.info("Exception reading file...", e);
            } finally {
                IOUtils.closeQuietly(is);
                IOUtils.closeQuietly(os);
                IOUtils.closeQuietly(sock);
            }
        }
    };
    log.info("Executing copy...");
    readPool.execute(runner);
}

From source file:org.apache.bookkeeper.util.LocalBookKeeper.java

public static boolean waitForServerUp(String hp, long timeout) {
    long start = MathUtils.now();
    String split[] = hp.split(":");
    String host = split[0];/*from www.  j av a2s.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(UTF_8));
                outstream.flush();

                reader = new BufferedReader(new InputStreamReader(sock.getInputStream(), UTF_8));
                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;
}