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.dbay.apns4j.impl.ApnsConnectionImpl.java

private void startErrorWorker() {
    Thread thread = new Thread(new Runnable() {

        @Override//ww w  .jav a 2  s .  c om
        public void run() {
            Socket curSocket = socket;
            try {
                if (!isSocketAlive(curSocket)) {
                    return;
                }
                InputStream socketIs = curSocket.getInputStream();
                byte[] res = new byte[ERROR_RESPONSE_BYTES_LENGTH];
                int size = 0;

                while (true) {
                    try {
                        size = socketIs.read(res);
                        if (size > 0 || size == -1) {
                            // break, when something was read or there is no
                            // data any more
                            break;
                        }
                    } catch (SocketTimeoutException e) {
                        // There is no data. Keep reading.
                        Thread.sleep(10);
                    }
                }

                int command = res[0];
                /**
                 * EN: error-response,close the socket and resent
                 * notifications CN: ???????
                 */
                if (size == res.length && command == Command.ERROR) {
                    int status = res[1];
                    int errorId = ApnsTools.parse4ByteInt(res[2], res[3], res[4], res[5]);

                    String token = ErrorResponse.desc(status);

                    // callback error token?
                    if (null != errorProcessHandler) {
                        errorProcessHandler.process(errorId, status, token);
                    }

                    if (logger.isInfoEnabled()) {
                        logger.info(String.format(
                                "%s, %s Received error response. status: %s, id: %s, error-desc: %s",
                                serviceName, connName, status, errorId, token));
                    }

                    Queue<PushNotification> resentQueue = new LinkedList<PushNotification>();

                    synchronized (lock) {
                        boolean found = false;
                        errorHappendedLastConn = true;
                        while (!notificationCachedQueue.isEmpty()) {
                            PushNotification pn = notificationCachedQueue.poll();
                            if (pn.getId() == errorId) {
                                found = true;
                            } else {
                                /**
                                 * https://developer.apple.com/library/ios/
                                 * documentation
                                 * /NetworkingInternet/Conceptual
                                 * /RemoteNotificationsPG
                                 * /Chapters/CommunicatingWIthAPS.html As
                                 * the document said, add the notifications
                                 * which need be resent to the queue. Igonre
                                 * the error one
                                 */
                                if (found) {
                                    resentQueue.add(pn);
                                }
                            }
                        }
                        if (!found) {
                            logger.warn(connName
                                    + " Didn't find error-notification in the queue. Maybe it's time to adjust cache length. id: "
                                    + errorId);
                        }
                    }
                    // resend notifications
                    if (!resentQueue.isEmpty()) {
                        ApnsResender.getInstance().resend(name, resentQueue);
                    }
                } else {
                    // ignore and continue reading
                    logger.error(
                            connName + " Unexpected command or size. commend: " + command + " , size: " + size);
                }
            } catch (Exception e) {
                // logger.error(connName + " " + e.getMessage(), e);
                logger.error(connName + " " + e.getMessage());
            } finally {
                /**
                 * EN: close the old socket although it may be closed once
                 * before. CN: ???
                 */
                closeSocket(curSocket);
            }
        }
    });

    thread.start();
}

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

public void run() {
    try {/*from   ww  w  .  j  av a2  s  .c o  m*/
        String line1 = input.readLine();
        switch (line1) {
        case "101 ping":
            ch_log.i("Client pinged us, responding with an acknowledgement.");
            output.write("102 pong");
            output.newLine();
            output.flush();
            output.close();
            break;
        case "302 request key update":
            ch_log.i("Client is requesting a key update.");
            KeyUpdate update = new KeyUpdate(ip);
            KeyUpdateManager.addPendingUpdate(connection_id, update);
            while (KeyUpdateManager.getUpdate(connection_id).isProcessed()) {
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            boolean accepted = KeyUpdateManager.getUpdate(connection_id).isAccepted();
            KeyUpdateManager.completeIncomingUpdate(connection_id, KeyUpdateManager.getUpdate(connection_id));
            if (accepted) {
                ch_log.i("Accepting key update");
                try {
                    output.write("303 update");
                    output.newLine();
                    output.flush();

                    String pubkeyB64 = input.readLine();

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

                    output.close();
                    input.close();

                    KeyManager.saveKeyByIP(ip, keyFactory.generatePublic(pubSpec));
                } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
                    ch_log.e("Error updating sender's key!");
                    e.printStackTrace();
                }
            } else {
                ch_log.i("Rejecting key update.");
                output.write("304 no update");
                output.newLine();
                output.flush();
                output.close();
            }
            break;
        case "301 getkey":
            ch_log.i("Client requested our public key, sending.");
            String pubkeyB64 = Base64.encodeBase64String(Main.getKeypair().getPublic().getEncoded());
            output.write(pubkeyB64);
            output.newLine();
            output.flush();
            output.close();
            break;
        case "200 encrypted message": //incoming encrypted message
            ch_log.i("Client sent an encrypted message, attempting verification and decryption.");
            PrivateKey privkey = Main.getKeypair().getPrivate();
            String cryptedMsg = input.readLine() + "\n" + input.readLine() + "\n" + input.readLine();

            ch_log.i("Checking for sender's public key.");
            if (KeyManager.checkIfIPKeyExists(ip)) {
                ch_log.i("Public key found.");
            } else {
                ch_log.i("Public key not found, requesting key from their server.");
                try {
                    Socket socketGetkey = new Socket();
                    socketGetkey.connect(new InetSocketAddress(InetAddress.getByName(ip), 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 sender_pubkeyB64 = inputGetkey.readLine();
                    byte[] pubEncoded = Base64.decodeBase64(sender_pubkeyB64);
                    X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubEncoded);
                    KeyFactory keyFactory = KeyFactory.getInstance("RSA");

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

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

            PacchatMessage message = MsgCrypto.decryptAndVerifyMessage(cryptedMsg, privkey,
                    KeyManager.loadKeyByIP(ip));

            String msg = message.getMessage();
            boolean verified = message.isVerified();
            boolean decrypted = message.isDecryptedSuccessfully();

            String ANSI_RESET = "\u001B[0m";
            String ANSI_CYAN = "\u001B[36m";
            String ANSI_BOLD = "\u001B[1m";
            if (verified && decrypted) {
                ch_log.i("Acknowledging message.");
                output.write("201 message acknowledgement");
                output.newLine();
                output.flush();
                output.close();
                System.out.println(ANSI_BOLD + ANSI_CYAN + "-----BEGIN MESSAGE-----" + ANSI_RESET);
                System.out.println(ANSI_BOLD + ANSI_CYAN + msg + ANSI_RESET);
                System.out.println(ANSI_BOLD + ANSI_CYAN + "-----END MESSAGE-----" + ANSI_RESET);
            } else if (!verified && decrypted) {
                ch_log.w("Notifying client that message authenticity was not verified.");
                output.write("203 unable to verify");
                output.newLine();
                output.flush();
                output.close();
                System.out.println(ANSI_BOLD + ANSI_CYAN + "-----BEGIN MESSAGE-----" + ANSI_RESET);
                System.out.println(ANSI_BOLD + ANSI_CYAN + msg + ANSI_RESET);
                System.out.println(ANSI_BOLD + ANSI_CYAN + "-----END MESSAGE-----" + ANSI_RESET);
            } else if (!verified) {
                ch_log.w("Notifying client that message could not be decrypted.");
                output.write("202 unable to decrypt");
                output.newLine();
                output.flush();
                output.close();
            }
            break;
        case "201 message acknowledgement":
            ch_log.i("Client sent an invalid message acknowledgement.");
            output.write("400 invalid transmission header");
            output.newLine();
            output.flush();
            output.close();
        case "202 unable to decrypt":
            ch_log.i("Client sent an invalid 'unable to decrypt' transmission.");
            output.write("400 invalid transmission header");
            output.newLine();
            output.flush();
            output.close();
        case "203 unable to verify":
            ch_log.i("Client sent an invalid 'unable to verify' transmission.");
            output.write("400 invalid transmission header");
            output.newLine();
            output.flush();
            output.close();
        default:
            ch_log.i("Client sent an invalid request header: " + line1);
            output.write("400 invalid transmission header");
            output.newLine();
            output.flush();
            output.close();
            break;
        }
    } catch (IOException e) {
        ch_log.e("Error in connection handler " + connection_id);
        e.printStackTrace();
    }
}

From source file:br.gov.frameworkdemoiselle.monitoring.internal.implementation.zabbix.ZabbixSender.java

/**
 * Retrieves all active checks configured in the server.
 * /*from   w ww. j  a va2 s.  c o m*/
 * @param hostname
 * @return   List<ActiveCheck>
 * @throws IOException
 */
public List<ActiveCheck> getActiveChecks(String hostname) throws IOException {

    List<ActiveCheck> list = new ArrayList<ActiveCheck>();

    Socket socket = null;
    OutputStream out = null;
    BufferedReader brin = null;

    try {
        socket = new Socket(zabbixServer, zabbixPort);
        socket.setSoTimeout(TIMEOUT);

        out = socket.getOutputStream();
        brin = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        // send request to Zabbix server and wait for the list of items to be returned
        out.write(createGetActiveChecksRequest(hostname));

        while (!socket.isClosed()) {
            String line = brin.readLine();

            if (line == null)
                break;

            // all active checks received
            if (line.startsWith(ZBX_EOF))
                break;

            list.add(parseActiveCheck(hostname, line));
        }

    } finally {
        if (brin != null) {
            brin.close();
        }
        if (out != null) {
            out.close();
        }
        if (socket != null) {
            socket.close();
        }
    }

    return list;
}

From source file:org.apache.ftpserver.RequestHandler.java

/**
 * Create secure socket./*from  w  ww .ja  va 2s  . c o m*/
 */
public void createSecureSocket(String protocol) throws Exception {

    // change socket to SSL socket
    ISsl ssl = m_fconfig.getDataConnectionConfig().getSSL();
    if (ssl == null) {
        throw new FtpException("Socket factory SSL not configured");
    }
    Socket ssoc = ssl.createSocket(protocol, m_controlSocket, false);

    // change streams
    m_reader = new BufferedReader(new InputStreamReader(ssoc.getInputStream(), "UTF-8"));
    m_writer.setControlSocket(ssoc);

    // set control socket
    m_controlSocket = ssoc;
}

From source file:com.irccloud.android.GingerbreadImageProxy.java

private HttpRequest readRequest(Socket client) {
    HttpRequest request = null;//from   ww w .j a  v  a 2s. co  m
    InputStream is;
    String firstLine;
    String range = null;
    String ua = null;
    try {
        is = client.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is), 8192);
        firstLine = reader.readLine();

        String line = null;

        do {
            line = reader.readLine();
            if (line != null && line.toLowerCase().startsWith("range: ")) {
                range = line.substring(7);
            }
            if (line != null && line.toLowerCase().startsWith("user-agent: ")) {
                ua = line.substring(12);
            }
        } while (line != null && reader.ready());
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error parsing request", e);
        return request;
    }

    if (firstLine == null) {
        Log.i(LOG_TAG, "Proxy client closed connection without a request.");
        return request;
    }

    StringTokenizer st = new StringTokenizer(firstLine);
    String method = st.nextToken();
    String uri = st.nextToken();
    String realUri = uri.substring(1);
    request = new BasicHttpRequest(method, realUri, new ProtocolVersion("HTTP", 1, 1));
    if (range != null)
        request.addHeader("Range", range);
    if (ua != null)
        request.addHeader("User-Agent", ua);
    return request;
}

From source file:org.psit.transwatcher.TransWatcher.java

@Override
public void run() {

    try {/*from w  w  w. j av  a  2s  . c om*/
        while (true) {

            String cardIP = connectAndGetCardIP();
            if (cardIP != null) {
                notifyMessage("Found SD card, IP: " + cardIP);

                // handshake successful, open permanent TCP connection
                // to listen to new images
                Socket newImageListenerSocket = null;
                try {
                    newImageListenerSocket = new Socket(cardIP, 5566);
                    newImageListenerSocket.setKeepAlive(true);
                    InputStream is = newImageListenerSocket.getInputStream();
                    byte[] c = new byte[1];
                    byte[] singleMessage = new byte[255];
                    int msgPointer = 0;

                    startConnectionKeepAliveWatchDog(newImageListenerSocket);

                    startImageDownloaderQueue(cardIP);

                    setState(State.LISTENING);

                    // loop to wait for new images
                    while (newImageListenerSocket.isConnected()) {
                        if (is.read(c) == 1) {
                            if (0x3E == c[0]) { // >
                                // start of filename
                                msgPointer = 0;
                            } else if (0x00 == c[0]) {
                                // end of filename
                                String msg = new String(Arrays.copyOfRange(singleMessage, 0, msgPointer));
                                notifyMessage("Image shot: " + msg);

                                // add to download queue
                                queue.add(msg);
                            } else {
                                // single byte. add to buffer
                                singleMessage[msgPointer++] = c[0];
                            }
                        }
                    }
                    setState(State.SEARCHING_CARD);
                } catch (IOException e) {
                    notifyMessage("Error during image notification connection!");
                } finally {
                    try {
                        newImageListenerSocket.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else {
                notifyMessage("No card found, retrying.");
            }
            Thread.sleep(2000);
        }
    } catch (InterruptedException e) {
        stopImageDownLoaderQueue();
        notifyMessage("Connection abandoned.");
    }

}

From source file:org.kjkoster.zapcat.test.ZabbixAgentProtocolTest.java

/**
 * Test that by default we have protocol version 1.4.
 * /*from  w  ww. j  a v  a 2 s . c  om*/
 * @throws Exception
 *             When the test failed.
 */
@Test
public void testDefault() throws Exception {
    final Agent agent = new ZabbixAgent();
    // give the agent some time to open the port
    Thread.sleep(100);
    final Socket socket = new Socket(InetAddress.getLocalHost(), ZabbixAgent.DEFAULT_PORT);

    final Writer out = new OutputStreamWriter(socket.getOutputStream());
    out.write("system.property[java.version]\n");
    out.flush();

    final InputStream in = socket.getInputStream();
    final byte[] buffer = new byte[1024];
    in.read(buffer);

    assertEquals('Z', buffer[0]);
    assertEquals('B', buffer[1]);
    assertEquals('X', buffer[2]);
    assertEquals('D', buffer[3]);
    // we'll take the rest for granted...

    socket.close();
    agent.stop();
}

From source file:org.kjkoster.zapcat.test.ZabbixAgentProtocolTest.java

/**
 * Test that we can use a Java system property to configure the protocol
 * version on the agent.//  w  ww.  j  ava2 s.c o  m
 * 
 * @throws Exception
 *             When the test failed.
 */
@Test
public void testSetTo11() throws Exception {
    System.setProperty(ZabbixAgent.PROTOCOL_PROPERTY, "1.1");
    assertEquals("1.1", System.getProperty(ZabbixAgent.PROTOCOL_PROPERTY));

    final Agent agent = new ZabbixAgent();
    // give the agent some time to open the port
    Thread.sleep(100);
    final Socket socket = new Socket(InetAddress.getLocalHost(), ZabbixAgent.DEFAULT_PORT);

    final Writer out = new OutputStreamWriter(socket.getOutputStream());
    out.write("system.property[java.version]\n");
    out.flush();

    final InputStream in = socket.getInputStream();
    final byte[] buffer = new byte[1024];
    in.read(buffer);

    final String version = System.getProperty("java.version");

    assertEquals(version.charAt(0), buffer[0]);
    assertEquals(version.charAt(1), buffer[1]);
    assertEquals(version.charAt(2), buffer[2]);
    assertEquals(version.charAt(3), buffer[3]);
    // we'll take the rest for granted...

    socket.close();
    agent.stop();
}

From source file:com.techcavern.pircbotz.PircBotZ.java

protected void changeSocket(Socket socket) throws IOException {
    this.socket = socket;
    this.inputReader = new BufferedReader(
            new InputStreamReader(socket.getInputStream(), configuration.getEncoding()));
    this.outputWriter = new OutputStreamWriter(socket.getOutputStream(), configuration.getEncoding());
}

From source file:com.annuletconsulting.homecommand.node.AsyncSend.java

@Override
public Loader<String> onCreateLoader(int id, Bundle args) {
    AsyncTaskLoader<String> loader = new AsyncTaskLoader<String>(activity) {
        @Override/*  w  w w . j  a  v  a 2s  .co  m*/
        public String loadInBackground() {
            StringBuffer instr = new StringBuffer();
            try {
                Socket connection = new Socket(ipAddr, port);
                BufferedOutputStream bos = new BufferedOutputStream(connection.getOutputStream());
                OutputStreamWriter osw = new OutputStreamWriter(bos, "US-ASCII");
                osw.write(formatJSON(command.toUpperCase()));
                osw.write(13);
                osw.flush();
                BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
                InputStreamReader isr = new InputStreamReader(bis, "US-ASCII");
                int c;
                while ((c = isr.read()) != 13)
                    instr.append((char) c);
                isr.close();
                bis.close();
                osw.close();
                bos.close();
                connection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return instr.toString();
        }
    };
    return loader;
}