Example usage for java.net Socket getInputStream

List of usage examples for java.net Socket getInputStream

Introduction

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

Prototype

public InputStream getInputStream() throws IOException 

Source Link

Document

Returns an input stream for this socket.

Usage

From source file:com.quigley.zabbixj.agent.active.ActiveThread.java

private void requestActiveChecks() throws Exception {
    if (log.isDebugEnabled()) {
        log.debug("Requesting a list of active checks from the server.");
    }/*from  w w w  .  j  a va 2 s . c  o m*/

    Socket socket = new Socket(serverAddress, serverPort);
    InputStream input = socket.getInputStream();
    OutputStream output = socket.getOutputStream();

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    JSONObject request = new JSONObject();
    request.put("request", "active checks");
    request.put("host", hostName);

    byte[] buffer = getRequest(request);

    output.write(buffer);
    output.flush();

    buffer = new byte[10240];
    int read = 0;
    while ((read = input.read(buffer, 0, 10240)) != -1) {
        baos.write(buffer, 0, read);
    }

    socket.close();

    JSONObject response = getResponse(baos.toByteArray());
    if (response.getString("response").equals("success")) {
        refreshFromActiveChecksResponse(response);

    } else {
        log.warn("Server reported a failure when requesting active checks:" + response.getString("info"));
    }

    lastRefresh = System.currentTimeMillis() / 1000;
}

From source file:org.apache.flume.source.TestNetcatSource.java

/**
 * Test that line above MaxLineLength are discarded
 *
 * @throws InterruptedException/*from   ww w. j a v a  2 s  .  c  o  m*/
 * @throws IOException
 */
@Test
public void testMaxLineLengthwithAck() throws InterruptedException, IOException {
    String encoding = "UTF-8";
    String ackEvent = "OK";
    String ackErrorEvent = "FAILED: Event exceeds the maximum length (10 chars, including newline)";
    startSource(encoding, "true", "1", "10");
    Socket netcatSocket = new Socket(localhost, selectedPort);
    LineIterator inputLineIterator = IOUtils.lineIterator(netcatSocket.getInputStream(), encoding);
    try {
        sendEvent(netcatSocket, "123456789", encoding);
        Assert.assertArrayEquals("Channel contained our event", "123456789".getBytes(defaultCharset),
                getFlumeEvent());
        Assert.assertEquals("Socket contained the Ack", ackEvent, inputLineIterator.nextLine());
        sendEvent(netcatSocket, english, encoding);
        Assert.assertEquals("Channel does not contain an event", null, getRawFlumeEvent());
        Assert.assertEquals("Socket contained the Error Ack", ackErrorEvent, inputLineIterator.nextLine());
    } finally {
        netcatSocket.close();
        stopSource();
    }
}

From source file:org.apache.axis.tools.ant.axis.RunAxisFunctionalTestsTask.java

/**
 * Make a socket to the url, and send the given string
 *///from   www  . jav a2  s  .co  m
private void sendOnSocket(String str) throws Exception {
    if (url == null)
        return;

    Socket sock = null;
    try {
        sock = new Socket(url.getHost(), url.getPort());
        sock.getOutputStream().write(new String(str).getBytes());
        // get a single byte response
        int i = sock.getInputStream().read();
    } catch (Exception ex) {
        throw ex;
    } /* finally {
      if (sock != null) {
          try {
              sock.close();
          } catch (IOException ex) {
              // ignore
          }
      }
      }*/
}

From source file:org.apache.flume.source.TestNetcatSource.java

/**
 * Test if an ack is sent for every event in the correct encoding
 *
 * @throws InterruptedException/* w w  w  .  j  a  va 2s .co m*/
 * @throws IOException
 */
@Test
public void testAck() throws InterruptedException, IOException {
    String encoding = "UTF-8";
    String ackEvent = "OK";
    startSource(encoding, "true", "1", "512");
    Socket netcatSocket = new Socket(localhost, selectedPort);
    LineIterator inputLineIterator = IOUtils.lineIterator(netcatSocket.getInputStream(), encoding);
    try {
        // Test on english text snippet
        for (int i = 0; i < 20; i++) {
            sendEvent(netcatSocket, english, encoding);
            Assert.assertArrayEquals("Channel contained our event", english.getBytes(defaultCharset),
                    getFlumeEvent());
            Assert.assertEquals("Socket contained the Ack", ackEvent, inputLineIterator.nextLine());
        }
        // Test on french text snippet
        for (int i = 0; i < 20; i++) {
            sendEvent(netcatSocket, french, encoding);
            Assert.assertArrayEquals("Channel contained our event", french.getBytes(defaultCharset),
                    getFlumeEvent());
            Assert.assertEquals("Socket contained the Ack", ackEvent, inputLineIterator.nextLine());
        }
    } finally {
        netcatSocket.close();
        stopSource();
    }
}

From source file:ch.cyberduck.core.ftp.FTPClient.java

public List<String> list(final FTPCmd command, final String pathname) throws IOException {
    this.pret(command, pathname);

    Socket socket = _openDataConnection_(command, pathname);

    BufferedReader reader = new BufferedReader(
            new InputStreamReader(socket.getInputStream(), getControlEncoding()));
    ArrayList<String> results = new ArrayList<String>();
    String line;/*  w w  w .j ava2 s .  c om*/
    while ((line = reader.readLine()) != null) {
        _commandSupport_.fireReplyReceived(-1, line);
        results.add(line);
    }

    reader.close();
    socket.close();

    if (!this.completePendingCommand()) {
        throw new FTPException(this.getReplyCode(), this.getReplyString());
    }
    return results;
}

From source file:com.jredrain.startup.Bootstrap.java

/**
 *
 * @throws Exception/*w  w  w. j  ava  2s  .c  o  m*/
 */

private void shutdown() throws Exception {
    /**
     * connect to startup socket and send stop command
     */
    Socket socket = new Socket("localhost", RedrainProperties.getInt("redrain.shutdown"));
    OutputStream os = socket.getOutputStream();
    PrintWriter pw = new PrintWriter(os);
    InputStream is = socket.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    pw.write(shutdown);
    pw.flush();
    socket.shutdownOutput();
    String reply = null;
    while (!((reply = br.readLine()) == null)) {
        logger.info("[redrain]shutdown:{}" + reply);
    }
    br.close();
    is.close();
    pw.close();
    os.close();
    socket.close();
}

From source file:com.quigley.zabbixj.agent.active.ActiveThread.java

private void sendMetrics(int delay, List<String> keyList) throws Exception {
    if (log.isDebugEnabled()) {
        String message = "Sending metrics for delay '" + delay + "' with keys: ";
        for (int i = 0; i < keyList.size(); i++) {
            if (i > 0) {
                message += ", ";
            }//from w w  w .  j  av a  2  s. c o  m
            message += keyList.get(i);
        }
        log.debug(message);
    }

    long clock = System.currentTimeMillis() / 1000;

    JSONObject metrics = new JSONObject();
    metrics.put("request", "agent data");

    JSONArray data = new JSONArray();
    for (String keyName : keyList) {
        JSONObject key = new JSONObject();
        key.put("host", hostName);
        key.put("key", keyName);
        try {
            Object value = metricsContainer.getMetric(keyName);
            key.put("value", value.toString());

        } catch (Exception e) {
            key.put("value", "ZBX_NOTSUPPORTED");
        }
        key.put("clock", "" + clock);

        data.put(key);
    }
    metrics.put("data", data);
    metrics.put("clock", "" + clock);

    Socket socket = new Socket(serverAddress, serverPort);
    InputStream input = socket.getInputStream();
    OutputStream output = socket.getOutputStream();

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    output.write(getRequest(metrics));
    output.flush();

    byte[] buffer = new byte[10240];
    int read = 0;
    while ((read = input.read(buffer, 0, 10240)) != -1) {
        baos.write(buffer, 0, read);
    }

    socket.close();

    JSONObject response = getResponse(baos.toByteArray());
    if (response.getString("response").equals("success")) {
        if (log.isDebugEnabled()) {
            log.debug("The server reported success '" + response.getString("info") + "'.");
        }
    } else {
        log.error("Failure!");
    }

    lastChecked.put(delay, clock);
}

From source file:gr.iit.demokritos.cru.cpserver.CPServer.java

public void StartCPServer() throws IOException, Exception {
    ServerSocket serversocket = new ServerSocket(port);
    System.out.println("Start CPServer");
    Bookeeper bk = new Bookeeper(this.properties);
    while (true) {
        System.out.println("Inside While");
        Socket connectionsocket = serversocket.accept();
        System.out.println("Inet");
        //InetAddress client = connectionsocket.getInetAddress();

        BufferedReader input = new BufferedReader(new InputStreamReader(connectionsocket.getInputStream()));
        DataOutputStream output = new DataOutputStream(connectionsocket.getOutputStream());

        httpHandler(input, output);/*from w  ww.  ja v a 2  s.com*/
    }
}

From source file:Main.IrcBot.java

public void serverConnect() {
    try {/*from w  w w  . j  a v a 2 s . c  om*/
        Socket ircSocket = new Socket(this.hostName, this.portNumber);

        if (ircSocket.isConnected()) {
            final PrintWriter out = new PrintWriter(ircSocket.getOutputStream(), true);
            final BufferedReader in = new BufferedReader(new InputStreamReader(ircSocket.getInputStream()));
            final BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));

            String userInput;
            String pass = "PASS *";
            String nick = "NICK " + this.name;
            String user = "USER " + this.name + " 8 * :" + this.name;
            String channel = "JOIN " + this.channel;
            Timer channelChecker = new Timer();

            out.println(pass);
            System.out.println("echo: " + in.readLine().toString());
            out.println(nick);
            System.out.println("echo: " + in.readLine().toString());
            out.println(user);
            System.out.println("echo: " + in.readLine().toString());
            out.println(channel);

            channelChecker.scheduleAtFixedRate(new TimerTask() {
                @Override
                public void run() {
                    try {
                        String userIn = in.readLine().toString();
                        ;
                        System.out.println(userIn);

                        if (userIn.contains("PING")) {
                            out.println("PONG hobana.freenode.net");
                        }

                        if (userIn.contains("http://pastebin.com")) {
                            //String[] urlCode = userIn.split("[http://pastebin.com]");

                            String url = "http://pastebin.com";
                            int indexStart = userIn.indexOf(url);
                            int indexStop = userIn.indexOf(" ", indexStart);
                            String urlCode = userIn.substring(indexStart, indexStop);
                            String pasteBinId = urlCode.substring(urlCode.indexOf("/", 9) + 1,
                                    urlCode.length());
                            System.out.println(pasteBinId);

                            IrcBot.postRequest(pasteBinId, out);
                        }

                    } catch (Exception j) {

                    }
                }
            }, 100, 100);

        } else {
            System.out.println("There was an error connecting to the IRC server: " + this.hostName
                    + " using port " + this.portNumber);
        }
    } catch (Exception e) {
        //System.out.println(e.getMessage());
    }
}

From source file:node.Mailbox.java

/**
 * Accept a message from a socket. Adds the message to the appropriate queue
 *///from  w  ww .j a va2  s .  c o  m
private void acceptMessage(Socket socket) {
    // get the source address
    String srcIP = socket.getInetAddress().getHostAddress();
    ObjectInputStream ois;
    try {
        InputStream is = socket.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        ois = new ObjectInputStream(bis);
        // now the Mailbox can block until it receives all message bytes
        // accept the message object
        AbstractMessage a = (AbstractMessage) ois.readObject();
        println("Received msg " + a.toString());
        // TODO MARK MESSAGE WITH OLD TIMESTAMP
        // save the srcIP for later. srcPort is already part of the message
        a.srcIP = srcIP;

        // cast to the appropriate message type
        if (a.msgType < MessageType.CONTROL) {
            // call the appropriate verifier, place the message in the queue
            // and call the appropriate message handler to reconstruct the
            // message over the network
            ControlMessage m = (ControlMessage) a;
            ctrlMsgsRecv.add(m);
        } else if (a.msgType < MessageType.EVOLVE) {
            EvolveMessage m = (EvolveMessage) a;
            evolveMsgsRecv.add(m);
        } else if (a.msgType < MessageType.DATA) {
            // TODO handle Data-specific messages (dataset/indexing
            // information, db webserver address, etc)
            throw new NoSuchMethodError("Handling DATA messages is not yet implemented");
        }
    } catch (StreamCorruptedException e) {
        println("Caught StreamCorruptedException: client must have terminated transmission", true);
    } catch (EOFException e) {
        println("Caught EOFException: client must have terminated transmission", true);
    } catch (IOException e) {
        log.log(Level.SEVERE, "Mailbox error: failed to accept message due to IOException", e);
        e.printStackTrace();
        log.severe(ExceptionUtils.getStackTrace(e));
    } catch (ClassNotFoundException e) {
        log.log(Level.SEVERE, "Mailbox error: failed to accept message due to ClassNotFoundException", e);
        e.printStackTrace();
        log.severe(ExceptionUtils.getStackTrace(e));
    }
}