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:edu.umass.cs.msocket.common.policies.GeoLoadProxyPolicy.java

/**
 * @throws Exception if a GNS error occurs
 * @see edu.umass.cs.msocket.common.policies.ProxySelectionPolicy#getNewProxy()
 *//*from  w ww .j a v a 2s .c o m*/
@Override
public List<InetSocketAddress> getNewProxy() throws Exception {
    // Lookup for active location service GUIDs
    final UniversalGnsClient gnsClient = gnsCredentials.getGnsClient();
    final GuidEntry guidEntry = gnsCredentials.getGuidEntry();
    JSONArray guids;
    try {
        guids = gnsClient.fieldRead(proxyGroupName, GnsConstants.ACTIVE_LOCATION_FIELD, guidEntry);
    } catch (Exception e) {
        throw new GnsException("Could not find active location services (" + e + ")");
    }

    // Try every location proxy in the list until one works
    for (int i = 0; i < guids.length(); i++) {
        // Retrieve the location service IP and connect to it
        String locationGuid = guids.getString(i);
        String locationIP = gnsClient.fieldRead(locationGuid, GnsConstants.LOCATION_SERVICE_IP, guidEntry)
                .getString(0);
        logger.fine("Contacting location service " + locationIP + " to request " + numProxies + " proxies");

        // Location IP is stored as host:port
        StringTokenizer st = new StringTokenizer(locationIP, ":");
        try {
            // Protocol is send the number of desired proxies and receive strings
            // containing proxy IP:port
            Socket s = new Socket(st.nextToken(), Integer.parseInt(st.nextToken()));
            ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
            ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
            oos.writeInt(numProxies);
            oos.flush();
            List<InetSocketAddress> result = new LinkedList<InetSocketAddress>();
            while (!s.isClosed() && result.size() < numProxies) {
                String proxyIP = ois.readUTF();
                StringTokenizer stp = new StringTokenizer(proxyIP, ":");
                result.add(new InetSocketAddress(stp.nextToken(), Integer.parseInt(stp.nextToken())));
            }
            if (!s.isClosed()) // We receive all the proxies we need, just close the
                               // socket
                s.close();
            return result;
        } catch (Exception e) {
            logger.info("Failed to obtain proxy from location service" + locationIP + " (" + e + ")");
        }
    }

    throw new GnsException("Could not find any location service to provide a geolocated proxy");
}

From source file:com.googlecode.jmxtrans.model.output.GraphiteWriter.java

@Override
public void internalWrite(Server server, Query query, ImmutableList<Result> results) throws Exception {
    Socket socket = null;
    PrintWriter writer = null;/*w w w  .  j  ava2s . c o  m*/

    try {
        socket = pool.borrowObject(address);
        writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), UTF_8), true);

        List<String> typeNames = this.getTypeNames();

        for (Result result : results) {
            log.debug("Query result: {}", result);
            Map<String, Object> resultValues = result.getValues();
            for (Entry<String, Object> values : resultValues.entrySet()) {
                Object value = values.getValue();
                if (isValidNumber(value)) {

                    String line = KeyUtils.getKeyString(server, query, result, values, typeNames, rootPrefix)
                            .replaceAll("[()]", "_") + " " + value.toString() + " " + result.getEpoch() / 1000
                            + "\n";
                    log.debug("Graphite Message: {}", line);
                    writer.write(line);
                } else {
                    onlyOnceLogger.infoOnce(
                            "Unable to submit non-numeric value to Graphite: [{}] from result [{}]", value,
                            result);
                }
            }
        }
    } finally {
        if (writer != null && writer.checkError()) {
            log.error("Error writing to Graphite, clearing Graphite socket pool");
            pool.invalidateObject(address, socket);
        } else {
            pool.returnObject(address, socket);
        }
    }
}

From source file:MailTest.java

/**
 * Sends the mail message that has been authored in the GUI.
 *//*from  w  w  w  .j  av a 2 s  .  c  o m*/
public void sendMail() {
    try {
        Socket s = new Socket(smtpServer.getText(), 25);

        InputStream inStream = s.getInputStream();
        OutputStream outStream = s.getOutputStream();

        in = new Scanner(inStream);
        out = new PrintWriter(outStream, true /* autoFlush */);

        String hostName = InetAddress.getLocalHost().getHostName();

        receive();
        send("HELO " + hostName);
        receive();
        send("MAIL FROM: <" + from.getText() + ">");
        receive();
        send("RCPT TO: <" + to.getText() + ">");
        receive();
        send("DATA");
        receive();
        send(message.getText());
        send(".");
        receive();
        s.close();
    } catch (IOException e) {
        comm.append("Error: " + e);
    }
}

From source file:com.apporiented.hermesftp.cmd.AbstractFtpCmdRetr.java

/**
 * {@inheritDoc}/*from  ww  w. j  a  v a  2 s . com*/
 */
public void execute() throws FtpCmdException {

    /* Get relevant information from context */
    File file = new File(getPathArg());
    int mode = getCtx().getTransmissionMode();
    int struct = getCtx().getStorageStructure();
    int type = getCtx().getDataType();
    String charset = type == DT_ASCII || type == DT_EBCDIC ? getCtx().getCharset() : null;
    long fileOffset = getAndResetFileOffset();
    getTransferRateLimiter().init(getCtx().getMaxDownloadRate());
    try {

        /* Check availability and access rights */
        doPerformAccessChecks(file);

        msgOut(MSG150);

        /* Wrap outbound data stream and call handler method */
        Socket dataSocket = getCtx().getDataSocketProvider().provideSocket();
        OutputStream dataOut = dataSocket.getOutputStream();
        if (struct == STRUCT_RECORD) {
            RecordWriteSupport recordOut = createRecOutputStream(dataOut, mode, charset);
            doRetrieveRecordData(recordOut, file, fileOffset);
        } else if (struct == STRUCT_FILE) {
            OutputStream fileOut = createOutputStream(dataOut, mode, charset);
            doRetrieveFileData(fileOut, file, fileOffset);
        } else {
            log.error("Unknown data type");
            msgOut(MSG550, "Unsupported data type");
            //dataSocket.shutdownOutput();
            return;
        }
        // TODO delegate event to FtpEventListener

        dataOut.flush();

    } catch (FtpQuotaException e) {
        msgOut(MSG550, e.getMessage());
        log.warn(e.getMessage());
    } catch (FtpPermissionException e) {
        msgOut(MSG550_PERM);
    } catch (UnsupportedEncodingException e) {
        msgOut(MSG550, "Unsupported Encoding: " + charset);
        log.error(e.toString());
    } catch (IOException e) {
        msgOut(MSG550);
        log.error(e.toString());
    } catch (RuntimeException e) {
        msgOut(MSG550);
        log.error(e.toString());
    } finally {
        getCtx().closeSockets();
    }
}

From source file:net.lightbody.bmp.proxy.jetty.http.ajp.AJP13Listener.java

/**
 * Create an AJP13Connection instance. This method can be used to override
 * the connection instance.//from   ww  w. j  a v a2s  .  c  o m
 * 
 * @param socket
 *            The underlying socket.
 */
protected AJP13Connection createConnection(Socket socket) throws IOException {
    return new AJP13Connection(this, socket.getInputStream(), socket.getOutputStream(), socket,
            getBufferSize());
}

From source file:Main.IrcBot.java

public void serverConnect() {
    try {//from  w ww  .j a  v  a 2 s .  c  o  m
        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:org.jfree.chart.demo.SocketThread.java

@Override
public void run() {
    // TODO Auto-generated method stub
    try {//ww w . j  av  a2  s .c  o m
        ServerSocket ss = new ServerSocket(4444);
        Socket socket = null;
        while (Islive) {
            System.out.println("Started :) ");
            socket = ss.accept(); /*  */
            System.out.println("Got a client :) ");

            InputStream sin = socket.getInputStream();
            OutputStream sout = socket.getOutputStream();

            in = new DataInputStream(sin);
            out = new DataOutputStream(sout);

            String line = null;

            while (true) {
                line = in.readUTF(); /*    */
                System.out.println("line start sending  = " + line);
                out.writeUTF(data);
                out.flush();
                line = in.readUTF();
                System.out.println(line);
                if (line == "finish")
                    break;
                else {
                    out.writeUTF("ok");
                    out.flush();
                }
            }
        }
        out.writeUTF("finish");
        out.flush();

        in.close();
        out.close();
        socket.close();
    } catch (Exception x) {

        errors += x.toString() + " ;\n";
        error_flag = true;
    }

}

From source file:hudson.plugins.chainreactorclient.ChainReactorInvalidServerException.java

public boolean connect(ChainReactorServer server) {
    try {//from   w  w w.  j ava2s  .c o  m
        InetSocketAddress sockaddr = server.getSocketAddress();
        Socket sock = new Socket();
        sock.setSoTimeout(2000);
        sock.connect(sockaddr, 2000);
        BufferedReader rd = new BufferedReader(new InputStreamReader(sock.getInputStream()));
        BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
        ensureValidServer(rd);
        logger.println("Connected to chain reactor server");
        sendBuildInfo(wr);
        rd.close();
        wr.close();
        sock.close();
    } catch (UnknownHostException uhe) {
        logError("Failed to resolve host: " + server.getUrl());
    } catch (SocketTimeoutException ste) {
        logError("Time out while trying to connect to " + server.toString());
    } catch (IOException ioe) {
        logError(ioe.getMessage());
    } catch (ChainReactorInvalidServerException crise) {
        logError(crise.getMessage());
    }

    return true;
}

From source file:net.mohatu.bloocoin.miner.RegisterClass.java

private void register() {
    try {/*from  www. ja  va  2  s. c om*/
        String result = new String();
        Socket sock = new Socket(this.url, this.port);
        String command = "{\"cmd\":\"register" + "\",\"addr\":\"" + addr + "\",\"pwd\":\"" + key + "\"}";
        DataInputStream is = new DataInputStream(sock.getInputStream());
        DataOutputStream os = new DataOutputStream(sock.getOutputStream());
        os.write(command.getBytes());
        os.flush();

        BufferedReader in = new BufferedReader(new InputStreamReader(is));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            result += inputLine;
        }

        is.close();
        os.close();
        sock.close();
        System.out.println(result);
        if (result.contains("\"success\": true")) {
            System.out.println("Registration successful: " + addr);
            saveBloostamp();
        } else if (result.contains("\"success\": false")) {
            System.out.println("Result: Failed");
            MainView.updateStatusText("Registration failed. ");
            System.exit(0);
        }
    } catch (UnknownHostException e) {
        System.out.println("Error: Unknown host.");
    } catch (IOException e) {
        System.out.println("Error: Network error.");
    }
}

From source file:org.fourthline.cling.transport.impl.apache.StreamServerImpl.java

protected boolean isConnectionOpen(Socket socket, byte[] heartbeat) {
    if (log.isLoggable(Level.FINE))
        log.fine("Checking if client connection is still open on: " + socket.getRemoteSocketAddress());
    try {//from  ww  w. j  av a2  s. co  m
        socket.getOutputStream().write(heartbeat);
        socket.getOutputStream().flush();
        return true;
    } catch (IOException ex) {
        if (log.isLoggable(Level.FINE))
            log.fine("Client connection has been closed: " + socket.getRemoteSocketAddress());
        return false;
    }
}