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.kyne.webby.bukkit.RTKModuleSocket.java

@Override
public void run() {
    LogHelper.info("Webby Socket (BukkitPlugin) is listening on port : " + this.serverSocket.getLocalPort());
    while (!this.serverSocket.isClosed()) {
        //         this.requestCount++;
        Socket clientSocket = null;
        ObjectInputStream ois = null;
        ObjectOutputStream oos = null;
        try {/*from   w ww  .  j  a v  a  2s.co  m*/
            clientSocket = this.serverSocket.accept();
            ois = new ObjectInputStream(clientSocket.getInputStream());
            oos = new ObjectOutputStream(clientSocket.getOutputStream());

            final WebbyLocalData request = (WebbyLocalData) ois.readObject();
            final WebbyLocalData response = this.handleRequest(request);
            oos.writeObject(response);
        } catch (final SocketException e) {
            LogHelper.warn("Socket has been closed. If bukkit is stopping or restarting, this is normal");
        } catch (final IOException e) {
            LogHelper.error("An error occured while waiting for connections", e);
        } catch (final ClassNotFoundException e) {
            LogHelper.error("Unsupported object was sent to Webby ", e);
        } finally {
            IOUtils.closeQuietly(ois);
            IOUtils.closeQuietly(oos);
            IOUtils.closeQuietly(clientSocket);
        }
    }
}

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  w w.  j a v  a  2 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.clustercontrol.hinemosagent.util.AgentConnectUtil.java

/**
 * common.agent.discovery.pingport ????????IP??
 *  ?TCP???????true?/*from w ww  . jav  a  2s  .com*/
 *  ?????????false?
 *
 * @param facilityId
 * @return
 * @throws UnknownHostException
 * @throws IOException
 */
public static boolean sendManagerDiscoveryInfo(String facilityId) throws UnknownHostException, IOException {
    String managerIpAddr = "";
    boolean successFlag = true;
    String agentIpAddr = "";
    int pingPort;

    // ???????????????????
    pingPort = HinemosPropertyUtil.getHinemosPropertyNum("common.agent.discovery.pingport", Long.valueOf(24005))
            .intValue();
    if (pingPort < 1 || pingPort > 65535) {
        return false;
    }
    // ???????IP?
    try {
        // DNS????(agent.connection.dnsname??) Hinemos ver 4.0.2?
        managerIpAddr = HinemosPropertyUtil.getHinemosPropertyStr("agent.connection.dnsname", "");

        // IP??(agent.connection.dnsname?)
        if (managerIpAddr == null || "".equals(managerIpAddr)) {
            managerIpAddr = HinemosPropertyUtil.getHinemosPropertyStr("agent.connection.ipaddres",
                    InetAddress.getLocalHost().getHostAddress());
        }
    } catch (UnknownHostException e) {
        throw e;
    }

    // FIXME ??????????????????????????????
    Socket socket = null;
    InputStream is = null;
    try {
        String sendDataStr = "managerIp=" + managerIpAddr + ",agentFacilityId=" + facilityId;
        byte[] data = sendDataStr.getBytes();
        byte[] msg = new byte[data.length];
        agentIpAddr = NodeProperty.getProperty(facilityId).getAvailableIpAddress();

        m_log.info("trying to establish connection to hinemos agent server at " + agentIpAddr + ":" + pingPort);

        socket = new Socket(agentIpAddr, pingPort);

        m_log.info("established the connection to the hinemos agent server at " + agentIpAddr);

        is = socket.getInputStream();
        OutputStream out = socket.getOutputStream();
        out.write(data);

        m_log.info("sent the message " + new String(data));

        // ???
        int totalBytesRcvd = 0;
        int bytesRcvd;

        while (totalBytesRcvd < data.length) {
            if ((bytesRcvd = is.read(msg, totalBytesRcvd, data.length - totalBytesRcvd)) == -1) {
                continue;
            }
            totalBytesRcvd += bytesRcvd;
        }
        m_log.info("received the message: " + new String(msg));
    } catch (Exception e) {
        successFlag = false;
        m_log.warn("facilityId: " + facilityId + ", " + e.getMessage());
    } finally {
        try {
            if (is != null) {
                is.close();
            }
            if (socket != null) {
                socket.close();
            }
        } catch (IOException e) {
            throw e;
        }
    }

    return successFlag;
}

From source file:com.atlassian.theplugin.commons.ssl.PluginSSLProtocolSocketFactory.java

/**
 * Copied from AXIS source code,//from   ww  w .j av  a  2s .c  om
 * original @author Davanum Srinivas (dims@yahoo.com)
 * THIS CODE STILL HAS DEPENDENCIES ON sun.* and com.sun.*
 */
public Socket create(final String host, final int port, final StringBuffer otherHeaders,
        final BooleanHolder useFullURL) throws Exception {

    PluginConfiguration config = ConfigurationFactory.getConfiguration();

    int sslPort = port;
    if (port == -1) {
        sslPort = EasySSLProtocolSocketFactory.SSL_PORT;
    }

    boolean hostInNonProxyList = false;
    TransportClientProperties tcp = TransportClientPropertiesFactory.create("https");

    if (tcp instanceof DefaultHTTPSTransportClientProperties) {
        hostInNonProxyList = ((DefaultHTTPSTransportClientProperties) tcp).getNonProxyHosts().contains("host");
    }
    //boolean hostInNonProxyList = super.isHostInNonPxyList(host, tcp.getNonProxyHosts());

    Socket sslSocket;
    if (!config.getGeneralConfigurationData().getUseIdeaProxySettings() || hostInNonProxyList
            || tcp.getProxyHost().length() == 0) {
        // direct SSL connection
        sslSocket = super.createSocket(host, sslPort);
    } else {
        int tunnelPort = (tcp.getProxyPort().length() != 0) ? Integer.parseInt(tcp.getProxyPort())
                : DEFAULT_PROXY_PORT;
        if (tunnelPort < 0) {
            tunnelPort = DEFAULT_PROXY_PORT;
        }

        // Create the regular socket connection to the proxy
        //Socket l = new Socket(new InetAddressImpl(tcp.getProxyHost()), tunnelPort);
        Socket tunnel = new Socket(InetAddress.getByName(tcp.getProxyHost()), tunnelPort);

        // The tunnel handshake method (condensed and made reflexive)
        OutputStream tunnelOutputStream = tunnel.getOutputStream();
        PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(tunnelOutputStream)));

        // More secure version... engage later?
        // PasswordAuthentication pa =
        // Authenticator.requestPasswordAuthentication(
        // InetAddress.getByName(tunnelHost),
        // tunnelPort, "SOCK", "Proxy","HTTP");
        // if(pa == null){
        // printDebug("No Authenticator set.");
        // }else{
        // printDebug("Using Authenticator.");
        // tunnelUser = pa.getUserName();
        // tunnelPassword = new String(pa.getPassword());
        // }
        out.print("CONNECT " + host + ":" + sslPort + " HTTP/1.0\r\n" + "User-Agent: AxisClient");
        if (tcp.getProxyUser().length() != 0 && tcp.getProxyPassword().length() != 0) {

            // add basic authentication header for the proxy
            String encodedPassword = XMLUtils
                    .base64encode((tcp.getProxyUser() + ":" + tcp.getProxyPassword()).getBytes());

            out.print("\nProxy-Authorization: Basic " + encodedPassword);
        }
        out.print("\nContent-Length: 0");
        out.print("\nPragma: no-cache");
        out.print("\r\n\r\n");
        out.flush();
        InputStream tunnelInputStream = tunnel.getInputStream();

        if (logger != null) {
            logger.debug(
                    Messages.getMessage("isNull00", "tunnelInputStream", "" + (tunnelInputStream == null)));
        }

        String replyStr = "";

        // Make sure to read all the response from the proxy to prevent SSL negotiation failure
        // Response message terminated by two sequential newlines
        int newlinesSeen = 0;
        boolean headerDone = false; /* Done on first newline */

        while (newlinesSeen < 2) {
            int i = tunnelInputStream.read();

            if (i < 0) {
                throw new IOException("Unexpected EOF from proxy");
            }
            if (i == '\n') {
                headerDone = true;
                ++newlinesSeen;
            } else if (i != '\r') {
                newlinesSeen = 0;
                if (!headerDone) {
                    replyStr += String.valueOf((char) i);
                }
            }
        }
        if (!StringUtils.startsWithIgnoreWhitespaces("HTTP/1.0 200", replyStr)
                && !StringUtils.startsWithIgnoreWhitespaces("HTTP/1.1 200", replyStr)) {
            throw new IOException(Messages.getMessage("cantTunnel00",
                    new String[] { tcp.getProxyHost(), "" + tunnelPort, replyStr }));
        }

        // End of condensed reflective tunnel handshake method
        sslSocket = super.createSocket(tunnel, host, port, true);

        if (logger != null) {
            logger.debug(Messages.getMessage("setupTunnel00", tcp.getProxyHost(), "" + tunnelPort));
        }

    }

    ((SSLSocket) sslSocket).startHandshake();
    if (logger != null) {
        logger.debug(Messages.getMessage("createdSSL00"));
    }
    return sslSocket;
}

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   ww  w  . j a  v  a 2 s . com

    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:fm.last.moji.tracker.impl.AbstractTrackerFactory.java

public Tracker newTracker(InetSocketAddress newAddress) throws TrackerException {
    log.debug("new {}()", TrackerImpl.class.getSimpleName());
    Tracker tracker = null;// w w w .ja v  a 2s .c o  m
    BufferedReader reader = null;
    Writer writer = null;
    Socket socket = null;
    try {
        socket = new Socket(netConfig.getProxy());
        socket.setSoTimeout(netConfig.getTrackerReadTimeout());
        log.debug("Connecting to: {}:", newAddress, socket.getPort());
        socket.connect(newAddress, netConfig.getTrackerConnectTimeout());
        reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        RequestHandler requestHandler = new RequestHandler(writer, reader);
        tracker = new TrackerImpl(socket, requestHandler);
    } catch (IOException e) {
        IOUtils.closeQuietly(reader);
        IOUtils.closeQuietly(writer);
        IOUtils.closeQuietly(socket);
        throw new TrackerException(e);
    }
    return tracker;
}

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

/**
 * Retrieves all active checks configured in the server.
 * //from  ww w.ja  v  a2  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:com.stratuscom.harvester.codebase.ClassServer.java

private boolean processRequest(Socket sock) {
    try {/*from w w  w .java  2  s . c  o m*/
        DataOutputStream out = new DataOutputStream(sock.getOutputStream());
        String req;
        try {
            req = getInput(sock, true);
        } catch (Exception e) {
            logger.log(Level.FINE, "reading request", e);
            return true;
        }
        if (req == null) {
            return true;
        }
        String[] args = new String[3];
        boolean get = req.startsWith("GET ");
        if (!get && !req.startsWith("HEAD ")) {
            processBadRequest(args, out);
        }
        String path = parsePathFromRequest(req, get);
        if (path == null) {
            return processBadRequest(args, out);
        }
        if (args != null) {
            args[0] = path;
        }
        args[1] = sock.getInetAddress().getHostName();
        args[2] = Integer.toString(sock.getPort());

        logger.log(Level.FINER,
                get ? MessageNames.CLASS_SERVER_RECEIVED_REQUEST : MessageNames.CLASS_SERVER_RECEIVED_PROBE,
                args);
        byte[] bytes;
        try {
            bytes = getBytes(path);
        } catch (Exception e) {
            logger.log(Level.WARNING, MessageNames.CLASS_SERVER_EXCEPTION_GETTING_BYTES, e);
            out.writeBytes("HTTP/1.0 500 Internal Error\r\n\r\n");
            out.flush();
            return true;
        }
        if (bytes == null) {
            logger.log(Level.FINE, MessageNames.CLASS_SERVER_NO_CONTENT_FOUND, path);
            out.writeBytes("HTTP/1.0 404 Not Found\r\n\r\n");
            out.flush();
            return true;
        }
        writeHeader(out, bytes);
        if (get) {
            out.write(bytes);
        }
        out.flush();
        return false;
    } catch (Exception e) {
        logger.log(Level.FINE, MessageNames.CLASS_SERVER_EXCEPTION_WRITING_RESPONSE, e);
    } finally {
        try {
            sock.close();
        } catch (IOException e) {
        }
    }
    return false;
}

From source file:com.github.stephanarts.cas.ticket.registry.support.JSONRPCServerTest.java

@Test
public void testInvalidZMQ() throws Exception {
    JSONRPCServer s = new JSONRPCServer("tcp://localhost:7901");
    s.start();// ww  w.  j a v  a 2 s.  c  o m

    java.net.Socket c = new java.net.Socket("localhost", 7901);
    java.io.PrintWriter out = new java.io.PrintWriter(c.getOutputStream(), true);
    out.print("BREAK_ZEROMQ");
    out.flush();
    c.close();

    s.cleanup();
}

From source file:com.chinamobile.bcbsp.pipes.BinaryProtocol.java

/**
 * Create a proxy object that will speak the binary protocol on a socket.
 * Upward messages are passed on the specified handler and downward downward
 * messages are public methods on this object.
 * @param sock/*w w  w . j a  v  a  2  s  .c  o m*/
 *        The socket to communicate on.
 * @param handler
 *        The handler for the received messages.
 *
 * @throws IOException e
 */

public BinaryProtocol(Socket sock, UpwardProtocol handler) throws IOException {
    OutputStream raw = sock.getOutputStream();
    // If we are debugging, save a copy of the downlink commands to a file
    // just for test
    // raw = new TeeOutputStream("downlink.txt", raw);
    outPutstream = new DataOutputStream(new BufferedOutputStream(raw, BUFFER_SIZE));
    uplink = new UplinkReaderThread(sock.getInputStream(), handler);
    uplink.setName("pipe-uplink-handler");
    uplink.start();
}