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.apporiented.hermesftp.session.impl.FtpSessionContextImpl.java

/**
 * {@inheritDoc}//from   ww w  . j  a va2  s.  c o  m
 */
public void setClientSocket(Socket clientSocket) throws IOException {
    this.clientSocket = clientSocket;
    this.clientResponseWriter = new LoggingWriter(new OutputStreamWriter(clientSocket.getOutputStream()), true);
    this.clientCmdReader = new LoggingReader(new InputStreamReader(clientSocket.getInputStream()));
}

From source file:com.salmonllc.ideTools.Tomcat50Engine.java

public void stopServer(String[] arguments, Tomcat50Bootstrap bootstrap) {

    if (_server == null) {
        // Create and execute our Digester
        Digester digester = createStopDigester();
        digester.setClassLoader(Thread.currentThread().getContextClassLoader());
        File file = configFile();
        try {//from w ww.ja v  a2 s.  c  o m
            InputSource is = new InputSource("file://" + file.getAbsolutePath());
            FileInputStream fis = new FileInputStream(file);
            is.setByteStream(fis);
            digester.push(this);
            digester.parse(is);
            fis.close();
        } catch (Exception e) {
            System.out.println("Catalina.stop: " + e);
            e.printStackTrace(System.out);
            System.exit(1);
        }
    }

    // Stop the existing server
    try {
        String host = "127.0.0.1";
        int port = 8005;
        String shutdown = "SHUTDOWN";

        if (_shutdown != null) {
            port = _shutdown.getPort();
            shutdown = _shutdown.getShutdown();
        }

        Socket socket = new Socket(host, port);
        OutputStream stream = socket.getOutputStream();

        for (int i = 0; i < shutdown.length(); i++)
            stream.write(shutdown.charAt(i));
        stream.flush();
        stream.close();
        socket.close();
        Thread.sleep(500);
    } catch (Exception e) {
        //System.out.println("Catalina.stop: " + e);
        //e.printStackTrace(System.out);
        //System.exit(1);
    }

    bootstrap.notifyComplete();

}

From source file:com.smartmarmot.orabbix.Sender.java

private void send(final String key, final String value) throws IOException {
    final StringBuilder message = new StringBuilder(head);
    //message.append(Base64.encode(key));
    message.append(base64Encode(key));//from www. j a v  a  2s  .c  om
    message.append(middle);
    //message.append(Base64.encode(value == null ? "" : value));
    message.append(base64Encode(value == null ? "" : value));
    message.append(tail);

    if (log.isDebugEnabled()) {
        SmartLogger.logThis(Level.DEBUG, "sending " + message);
    }

    Socket zabbix = null;
    OutputStreamWriter out = null;
    InputStream in = null;
    Enumeration<String> serverlist = zabbixServers.keys();

    while (serverlist.hasMoreElements()) {
        String zabbixServer = serverlist.nextElement();
        try {
            zabbix = new Socket(zabbixServer, zabbixServers.get(zabbixServer).intValue());
            zabbix.setSoTimeout(TIMEOUT);

            out = new OutputStreamWriter(zabbix.getOutputStream());
            out.write(message.toString());
            out.flush();

            in = zabbix.getInputStream();
            final int read = in.read(response);
            if (log.isDebugEnabled()) {
                SmartLogger.logThis(Level.DEBUG, "received " + new String(response));
            }
            if (read != 2 || response[0] != 'O' || response[1] != 'K') {
                SmartLogger.logThis(Level.WARN,
                        "received unexpected response '" + new String(response) + "' for key '" + key + "'");
            }
        } catch (Exception ex) {
            SmartLogger.logThis(Level.ERROR, "Error contacting Zabbix server " + zabbixServer + "  on port "
                    + zabbixServers.get(zabbixServer));
        }

        finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
            if (zabbix != null) {
                zabbix.close();
            }

        }
    }
}

From source file:com.mirth.connect.connectors.mllp.MllpMessageDispatcher.java

protected void write(Socket socket, String data) throws Exception {
    LlpProtocol protocol = connector.getLlpProtocol();
    BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream(), connector.getBufferSize());
    protocol.write(bos, data.getBytes(connector.getCharsetEncoding()));
    bos.flush();/* w  w w . j  a  v  a 2  s . c o  m*/
}

From source file:com.mirth.connect.connectors.mllp.MllpMessageDispatcher.java

protected void write(Socket socket, byte[] data) throws IOException {
    LlpProtocol protocol = connector.getLlpProtocol();
    BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream(), connector.getBufferSize());
    protocol.write(bos, data);//from  w ww.  ja  va  2  s.c om
    bos.flush();
}

From source file:net.sbbi.upnp.ServicesEventing.java

/**
 * Unregisters events notifications from a service
 * @param service the service that need to be unregistered
 * @param handler the handler that registered for this service
 * @return true if unregistered false otherwise ( the given handler never registred for the given service )
 * @throws IOException if some IOException error happens during coms with the device
 *///from w  ww  . j  a  v  a2 s.  c o m
public boolean unRegister(UPNPService service, ServiceEventHandler handler) throws IOException {

    URL eventingLoc = service.getEventSubURL();

    if (eventingLoc != null) {

        Subscription sub = lookupSubscriber(service, handler);
        if (sub != null) {
            synchronized (registered) {
                registered.remove(sub);
            }
            if (registered.size() == 0) {
                stopServicesEventingThread();
            }

            StringBuffer packet = new StringBuffer(64);
            packet.append("UNSUBSCRIBE  ").append(eventingLoc.getFile()).append(" HTTP/1.1\r\n");
            packet.append("HOST: ").append(eventingLoc.getHost()).append(":").append(eventingLoc.getPort())
                    .append("\r\n");
            packet.append("SID: ").append(sub.sub.getSID()).append("\r\n\r\n");
            Socket skt = new Socket(eventingLoc.getHost(), eventingLoc.getPort());
            skt.setSoTimeout(30000); // 30 secs timeout according to the specs
            if (log.isDebugEnabled())
                log.debug(packet);
            OutputStream out = skt.getOutputStream();
            out.write(packet.toString().getBytes());
            out.flush();

            InputStream in = skt.getInputStream();
            StringBuffer data = new StringBuffer();
            int readen = 0;
            byte[] buffer = new byte[256];
            while ((readen = in.read(buffer)) != -1) {
                data.append(new String(buffer, 0, readen));
            }
            in.close();
            out.close();
            skt.close();
            if (log.isDebugEnabled())
                log.debug(data.toString());
            if (data.toString().trim().length() > 0) {
                HttpResponse resp = new HttpResponse(data.toString());
                if (resp.getHeader().startsWith("HTTP/1.1 200 OK")) {
                    return true;
                }
            }
        }
    }
    return false;
}

From source file:com.hijacker.FeedbackDialog.java

void attemptSend() {
    feedbackView.setError(null);//from ww  w .  ja va 2  s . c om
    if (!internetAvailable(FeedbackDialog.this.getActivity())) {
        Log.d("HIJACKER/SendLog", "No internet connection");
        Snackbar.make(dialogView, getString(R.string.no_internet), Snackbar.LENGTH_SHORT).show();
        return;
    }

    final String feedback = feedbackView.getText().toString();
    if (feedback.equals("")) {
        feedbackView.setError(getString(R.string.field_required));
        feedbackView.requestFocus();
        return;
    }
    final String email = emailView.getText().toString();
    if (!email.equals("")) {
        pref_edit.putString("user_email", email);
        pref_edit.commit();
    }

    progress.setIndeterminate(true);

    new Thread(new Runnable() {
        @Override
        public void run() {
            Looper.prepare();
            FeedbackDialog.this.setCancelable(false);
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    progress.setIndeterminate(false);
                }
            };
            Socket socket = connect();
            if (socket == null) {
                runInHandler(runnable);
                Snackbar.make(dialogView, getString(R.string.server_error), Snackbar.LENGTH_SHORT).show();
                return;
            }

            try {
                PrintWriter in = new PrintWriter(socket.getOutputStream());
                BufferedReader out = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                in.print(REQ_FEEDBACK + '\n');
                in.flush();

                String buffer;
                buffer = out.readLine();
                if (buffer != null) {
                    if (!buffer.equals(ANS_POSITIVE)) {
                        runInHandler(runnable);
                        Snackbar.make(dialogView, getString(R.string.server_denied), Snackbar.LENGTH_SHORT)
                                .show();
                        return;
                    }
                } else {
                    runInHandler(runnable);
                    Snackbar.make(dialogView, getString(R.string.connection_closed), Snackbar.LENGTH_SHORT)
                            .show();
                    return;
                }

                in.print("Hijacker feedback - " + new Date().toString() + "\n");
                in.print("User email: " + email + '\n');
                in.print("App version: " + versionName + " (" + versionCode + ")\n");
                in.print("Android version: " + Build.VERSION.SDK_INT + '\n');
                in.print("Device model: " + deviceModel + '\n');
                in.print("\nFeedback:\n");
                in.print(feedback + '\n');
                in.print("EOF\n");
                in.flush();

                if (report != null && include_report.isChecked()) {
                    in.print(REQ_REPORT + '\n');
                    in.flush();

                    buffer = out.readLine();
                    if (buffer != null) {
                        if (!buffer.equals(ANS_POSITIVE)) {
                            Snackbar.make(dialogView, getString(R.string.server_denied), Toast.LENGTH_SHORT)
                                    .show();
                            runInHandler(runnable);
                            return;
                        }
                    } else {
                        Snackbar.make(dialogView, getString(R.string.connection_closed), Toast.LENGTH_SHORT)
                                .show();
                        runInHandler(runnable);
                        return;
                    }

                    BufferedReader fileReader = new BufferedReader(new FileReader(report));

                    in.print("User email: " + email + '\n');
                    in.flush();
                    buffer = fileReader.readLine();
                    while (buffer != null) {
                        in.print(buffer + '\n');
                        in.flush();
                        buffer = fileReader.readLine();
                    }
                    in.print("EOF\n");
                    in.flush();
                }
                in.print(REQ_EXIT + '\n');
                in.flush();

                in.close();
                out.close();
                socket.close();
                dismissAllowingStateLoss();
            } catch (IOException e) {
                Log.e("HIJACKER/FeedbackOnSend", e.toString());
                Snackbar.make(dialogView, getString(R.string.unknown_error), Snackbar.LENGTH_SHORT).show();
            } finally {
                runInHandler(runnable);
                FeedbackDialog.this.setCancelable(true);
            }
        }
    }).start();
}

From source file:com.tasktop.c2c.server.ssh.server.commands.AbstractInteractiveProxyCommand.java

protected void performCommand(Environment env, ProjectService service, String projectId, String path,
        String requestPath, RequestHeadersSupport headers) throws CommandException {
    String internalProxyUri = service.computeInternalProxyBaseUri(false);
    if (internalProxyUri == null) {
        throw new IllegalStateException();
    }//from ww  w . java2s.  c o m
    URI targetUri;
    try {
        if (!internalProxyUri.endsWith("/")) {
            internalProxyUri += "/";
        }
        internalProxyUri += getName() + '/' + path;

        targetUri = new URI(internalProxyUri);
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
    String host = targetUri.getHost();
    int port = targetUri.getPort();
    if (port < 0) {
        port = 80;
    }
    if (targetUri.getScheme() == null || !targetUri.getScheme().equalsIgnoreCase("http")) {
        throw new IllegalStateException("scheme " + targetUri.getScheme() + " is not supported");
    }
    HeaderGroup headerGroup = computeHeaders(targetUri);
    for (Entry<String, List<String>> headerEntry : headers.getRequestHeaders().entrySet()) {
        for (String value : headerEntry.getValue()) {
            headerGroup.addHeader(new Header(headerEntry.getKey(), value));
        }
    }
    getLogger().info("Proxying " + getName() + " to " + targetUri);
    try {
        Socket socket = socketFactory.openConnection(host, port);
        try {
            // initiate an HTTP request with Transfer-Encoding: chunked
            OutputStream proxyOut = socket.getOutputStream();
            emitHttpRequestLine(proxyOut, targetUri);
            emitHeaders(proxyOut, headerGroup);

            proxyOut.flush();

            List<Callable<Void>> tasks = new ArrayList<Callable<Void>>(3);
            FlushingChunkedOutputStream chunkedRequestOut = new FlushingChunkedOutputStream(proxyOut);
            tasks.add(new InputPipe(in, chunkedRequestOut, bufferSize, Thread.currentThread()).flush(true));

            // start these pipes
            ExecutorService executor = Executors.newFixedThreadPool(tasks.size());
            try {
                for (Callable<Void> task : tasks) {
                    executor.submit(task);
                }

                InputStream proxyInput = socket.getInputStream();
                try {
                    readHttpResponse(proxyInput);
                    MultiplexingInputStream input = new MultiplexingInputStream(
                            new ChunkedInputStream(proxyInput));
                    for (;;) {
                        PacketType packetType = input.getPacketType();
                        if (packetType == null) {
                            break;
                        }
                        int length = input.getPacketLength();

                        processData(input, packetType, length);
                    }
                } finally {
                    try {
                        executor.shutdown();
                        executor.awaitTermination(1000L, TimeUnit.MILLISECONDS);
                    } catch (InterruptedException e) {
                        // ignore
                    }
                }
            } finally {
                executor.shutdownNow();
                try {
                    executor.awaitTermination(3000L, TimeUnit.MILLISECONDS);
                } catch (InterruptedException e) {
                    // ignore
                }
                Thread.interrupted();

                try {
                    // attempt to close the chunked output, since this will make us a well-behaved client
                    // by sending the closing chunk.
                    chunkedRequestOut.close();
                } catch (Throwable t) {
                    // ignore
                }
            }
        } finally {
            socket.close();
        }
    } catch (ConnectException e) {
        getLogger().error(e.getMessage(), e);
        throw new CommandException(-1, "Service temporarily unavailable");
    } catch (IOException e) {
        getLogger().warn(e.getMessage(), e);
        throw new CommandException(-1, e.getMessage());
    }
}

From source file:net.sbbi.upnp.ServicesEventing.java

/**
 * Register state variable events notification for a device service
 * @param service the service to register with
 * @param handler the registrant object// w  ww.  j a v a2  s. c o  m
 * @param subscriptionDuration subscription time in seconds, -1 for infinite time
 * @return an ServiceEventSubscription object instance containing all the required info or null if no subscription done
 * @throws IOException if some IOException error happens during coms with the device
 */
public ServiceEventSubscription registerEvent(UPNPService service, ServiceEventHandler handler,
        int subscriptionDuration) throws IOException {

    URL eventingLoc = service.getEventSubURL();

    if (eventingLoc != null) {

        if (!inService)
            startServicesEventingThread();
        String duration = Integer.toString(subscriptionDuration);
        if (subscriptionDuration == -1) {
            duration = "infinite";
        }

        Subscription sub = lookupSubscriber(service, handler);
        if (sub != null) {
            // allready registered let's try to unregister it
            unRegister(service, handler);
        }

        StringBuffer packet = new StringBuffer(64);
        packet.append("SUBSCRIBE ").append(eventingLoc.getFile()).append(" HTTP/1.1\r\n");
        packet.append("HOST: ").append(eventingLoc.getHost()).append(":").append(eventingLoc.getPort())
                .append("\r\n");
        packet.append("CALLBACK: <http://").append(InetAddress.getLocalHost().getHostAddress()).append(":")
                .append(daemonPort).append("").append(eventingLoc.getFile()).append(">\r\n");
        packet.append("NT: upnp:event\r\n");
        packet.append("Connection: close\r\n");
        packet.append("TIMEOUT: Second-").append(duration).append("\r\n\r\n");

        Socket skt = new Socket(eventingLoc.getHost(), eventingLoc.getPort());
        skt.setSoTimeout(30000); // 30 secs timeout according to the specs
        if (log.isDebugEnabled())
            log.debug(packet);
        OutputStream out = skt.getOutputStream();
        out.write(packet.toString().getBytes());
        out.flush();

        InputStream in = skt.getInputStream();
        StringBuffer data = new StringBuffer();
        int readen = 0;
        byte[] buffer = new byte[256];
        while ((readen = in.read(buffer)) != -1) {
            data.append(new String(buffer, 0, readen));
        }
        in.close();
        out.close();
        skt.close();
        if (log.isDebugEnabled())
            log.debug(data.toString());
        if (data.toString().trim().length() > 0) {
            HttpResponse resp = new HttpResponse(data.toString());

            if (resp.getHeader().startsWith("HTTP/1.1 200 OK")) {
                String sid = resp.getHTTPHeaderField("SID");
                String actualTimeout = resp.getHTTPHeaderField("TIMEOUT");
                int durationTime = 0;
                // actualTimeout = Second-xxx or Second-infinite
                if (!actualTimeout.equalsIgnoreCase("Second-infinite")) {
                    durationTime = Integer.parseInt(actualTimeout.substring(7));
                }
                sub = new Subscription();
                sub.handler = handler;
                sub.sub = new ServiceEventSubscription(service.getServiceType(), service.getServiceId(),
                        service.getEventSubURL(), sid, skt.getInetAddress(), durationTime);
                synchronized (registered) {
                    registered.add(sub);
                }
                return sub.sub;
            }
        }
    }
    return null;

}

From source file:io.undertow.server.handlers.ReceiverTestCase.java

@Test
public void testAsyncReceiveWholeBytesFailed() throws Exception {
    EXCEPTIONS.clear();// w ww.  jav a2s . c  om
    Socket socket = new Socket();
    socket.connect(DefaultServer.getDefaultServerAddress());

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < 10000; ++i) {
        sb.append("hello world\r\n");
    }
    //send a large request that is too small, then kill the socket
    String request = "POST /fullbytes HTTP/1.1\r\nHost:localhost\r\nContent-Length:" + sb.length() + 100
            + "\r\n\r\n" + sb.toString();
    OutputStream outputStream = socket.getOutputStream();

    outputStream.write(request.getBytes("US-ASCII"));
    socket.getInputStream().close();
    outputStream.close();

    IOException e = EXCEPTIONS.poll(2, TimeUnit.SECONDS);
    Assert.assertNotNull(e);

}