Search in sources :

Example 16 with OutputStream

use of java.io.OutputStream in project camel by apache.

the class LZFDataFormat method marshal.

@Override
public void marshal(final Exchange exchange, final Object graph, final OutputStream stream) throws Exception {
    InputStream is = exchange.getContext().getTypeConverter().mandatoryConvertTo(InputStream.class, exchange, graph);
    OutputStream compressedOutput = parallelCompression ? new PLZFOutputStream(stream) : new LZFOutputStream(stream);
    try {
        IOHelper.copy(is, compressedOutput);
    } finally {
        // must close all input streams
        IOHelper.close(is, compressedOutput);
    }
}
Also used : PLZFOutputStream(com.ning.compress.lzf.parallel.PLZFOutputStream) LZFInputStream(com.ning.compress.lzf.LZFInputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) LZFOutputStream(com.ning.compress.lzf.LZFOutputStream) PLZFOutputStream(com.ning.compress.lzf.parallel.PLZFOutputStream) LZFOutputStream(com.ning.compress.lzf.LZFOutputStream) PLZFOutputStream(com.ning.compress.lzf.parallel.PLZFOutputStream)

Example 17 with OutputStream

use of java.io.OutputStream in project camel by apache.

the class MinaTcpLineDelimiterUsingPlainSocketTest method sendAndReceive.

private String sendAndReceive(String input) throws IOException {
    byte[] buf = new byte[128];
    Socket soc = new Socket();
    soc.connect(new InetSocketAddress("localhost", getPort()));
    // Send message using plain Socket to test if this works
    OutputStream os = null;
    InputStream is = null;
    try {
        os = soc.getOutputStream();
        // must append MAC newline at the end to flag end of textline to Camel-Mina
        os.write((input + "\r").getBytes());
        is = soc.getInputStream();
        int len = is.read(buf);
        if (len == -1) {
            // no data received
            return null;
        }
    } finally {
        IOHelper.close(is, os);
        soc.close();
    }
    // convert the buffer to chars
    StringBuilder sb = new StringBuilder();
    for (byte b : buf) {
        char ch = (char) b;
        if (ch == '\r' || ch == 0) {
            // use MAC delimiter denotes end of text (added in the end in the processor below)
            break;
        } else {
            sb.append(ch);
        }
    }
    return sb.toString();
}
Also used : InetSocketAddress(java.net.InetSocketAddress) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) Socket(java.net.Socket)

Example 18 with OutputStream

use of java.io.OutputStream in project camel by apache.

the class Mina2TcpLineDelimiterUsingPlainSocketTest method sendAndReceive.

private String sendAndReceive(String input) throws IOException {
    byte[] buf = new byte[128];
    Socket soc = new Socket();
    soc.connect(new InetSocketAddress("localhost", getPort()));
    // Send message using plain Socket to test if this works
    OutputStream os = null;
    InputStream is = null;
    try {
        os = soc.getOutputStream();
        // must append MAC newline at the end to flag end of textline to camel-mina2
        os.write((input + "\r").getBytes());
        is = soc.getInputStream();
        int len = is.read(buf);
        if (len == -1) {
            // no data received
            return null;
        }
    } finally {
        IOHelper.close(is, os);
        soc.close();
    }
    // convert the buffer to chars
    StringBuilder sb = new StringBuilder();
    for (byte b : buf) {
        char ch = (char) b;
        if (ch == '\r' || ch == 0) {
            // use MAC delimiter denotes end of text (added in the end in the processor below)
            break;
        } else {
            sb.append(ch);
        }
    }
    return sb.toString();
}
Also used : InetSocketAddress(java.net.InetSocketAddress) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) Socket(java.net.Socket)

Example 19 with OutputStream

use of java.io.OutputStream in project camel by apache.

the class MllpSocketWriter method writeEnvelopedPayload.

public void writeEnvelopedPayload(byte[] hl7MessageBytes, byte[] hl7AcknowledgementBytes) throws MllpException {
    if (socket == null) {
        final String errorMessage = "Socket is null";
        if (isAcknowledgementWriter()) {
            throw new MllpAcknowledgementDeliveryException(errorMessage, hl7MessageBytes, hl7AcknowledgementBytes);
        } else {
            throw new MllpWriteException(errorMessage, hl7MessageBytes);
        }
    } else if (!socket.isConnected()) {
        final String errorMessage = "Socket is not connected";
        if (isAcknowledgementWriter()) {
            throw new MllpAcknowledgementDeliveryException(errorMessage, hl7MessageBytes, hl7AcknowledgementBytes);
        } else {
            throw new MllpWriteException(errorMessage, hl7MessageBytes);
        }
    } else if (socket.isClosed()) {
        final String errorMessage = "Socket is closed";
        if (isAcknowledgementWriter()) {
            throw new MllpAcknowledgementDeliveryException(errorMessage, hl7MessageBytes, hl7AcknowledgementBytes);
        } else {
            throw new MllpWriteException(errorMessage, hl7MessageBytes);
        }
    }
    OutputStream socketOutputStream = null;
    try {
        socketOutputStream = socket.getOutputStream();
    } catch (IOException e) {
        final String errorMessage = "Failed to retrieve the OutputStream from the Socket";
        if (isAcknowledgementWriter()) {
            throw new MllpAcknowledgementDeliveryException(errorMessage, hl7MessageBytes, hl7AcknowledgementBytes);
        } else {
            throw new MllpWriteException(errorMessage, hl7MessageBytes, hl7AcknowledgementBytes);
        }
    }
    try {
        socketOutputStream.write(START_OF_BLOCK);
    } catch (IOException e) {
        final String errorMessage = "Failed to write the START_OF_BLOCK to the Socket's OutputStream";
        if (isAcknowledgementWriter()) {
            throw new MllpAcknowledgementDeliveryException(errorMessage, hl7MessageBytes, hl7AcknowledgementBytes);
        } else {
            throw new MllpWriteException(errorMessage, hl7MessageBytes, hl7AcknowledgementBytes);
        }
    }
    if (isAcknowledgementWriter()) {
        if (hl7AcknowledgementBytes == null) {
            log.warn("HL7 Acknowledgement payload is null - sending empty MLLP payload");
        } else if (hl7AcknowledgementBytes.length <= 0) {
            log.warn("HL7 Acknowledgement payload is empty - sending empty MLLP payload");
        } else {
            try {
                socketOutputStream.write(hl7AcknowledgementBytes);
            } catch (IOException ioEx) {
                throw new MllpAcknowledgementDeliveryException("Failed to write the HL7 Acknowledgement payload to the Socket's OutputStream", hl7MessageBytes, hl7AcknowledgementBytes, ioEx);
            }
        }
    } else {
        if (hl7MessageBytes == null) {
            log.warn("HL7 Message payload is null - sending empty MLLP payload");
        } else if (hl7MessageBytes.length <= 0) {
            log.warn("HL7 Message payload is empty - sending empty MLLP payload");
        } else {
            try {
                socketOutputStream.write(hl7MessageBytes);
            } catch (IOException ioEx) {
                throw new MllpWriteException("Failed to write the HL7 Message payload to the Socket's OutputStream", hl7MessageBytes, hl7AcknowledgementBytes, ioEx);
            }
        }
    }
    try {
        socketOutputStream.write(PAYLOAD_TERMINATOR);
        socketOutputStream.flush();
    } catch (IOException e) {
        final String errorMessage = "Failed to write the END_OF_BLOCK and END_OF_DATA to the Socket's OutputStream";
        if (isAcknowledgementWriter()) {
            throw new MllpAcknowledgementDeliveryException(errorMessage, hl7MessageBytes, hl7AcknowledgementBytes);
        } else {
            throw new MllpWriteException(errorMessage, hl7MessageBytes, hl7AcknowledgementBytes);
        }
    }
}
Also used : MllpWriteException(org.apache.camel.component.mllp.MllpWriteException) OutputStream(java.io.OutputStream) MllpAcknowledgementDeliveryException(org.apache.camel.component.mllp.MllpAcknowledgementDeliveryException) IOException(java.io.IOException)

Example 20 with OutputStream

use of java.io.OutputStream in project camel by apache.

the class JavaSocketTests method testSocketReadOnClosedConnection.

@Test
public void testSocketReadOnClosedConnection() throws Exception {
    final Thread acceptThread = new Thread() {

        Logger log = LoggerFactory.getLogger("acceptThread");

        @Override
        public void run() {
            boolean running = true;
            try {
                Socket echoSocket = serverSocket.accept();
                log.info("Accepted connection: {}", echoSocket.getInetAddress());
                echoSocket.setSoTimeout(2000);
                while (echoSocket.isConnected() && !echoSocket.isClosed()) {
                    StringBuilder responseBuilder = new StringBuilder(500);
                    InputStream reader = echoSocket.getInputStream();
                    OutputStream writer = echoSocket.getOutputStream();
                    do {
                        int readByte = -1;
                        int available = -1;
                        try {
                            available = reader.available();
                            log.info("InputStream.available returned {}", available);
                            readByte = reader.read();
                            log.trace("Processing byte: {}", readByte);
                            switch(readByte) {
                                case -1:
                                    if (echoSocket.isConnected() && !echoSocket.isClosed()) {
                                        log.info("Available returned {}", reader.available());
                                        log.warn("Socket claims to still be open, but END_OF_STREAM received - closing echoSocket");
                                        try {
                                            echoSocket.close();
                                        } catch (Exception ex) {
                                            log.warn("Exception encountered closing echoSocket after END_OF_STREAM received", ex);
                                        }
                                    }
                                    running = false;
                                    break;
                                case 10:
                                    log.info("Complete Message - Sending Response");
                                    byte[] response = responseBuilder.toString().getBytes();
                                    responseBuilder.setLength(0);
                                    writer.write(response, 0, response.length);
                                    writer.write('\n');
                                    break;
                                default:
                                    responseBuilder.append((char) readByte);
                            }
                        } catch (SocketTimeoutException timeoutEx) {
                            log.info("Timeout reading data - available returned {}", available);
                        }
                    } while (echoSocket.isConnected() && !echoSocket.isClosed());
                }
            } catch (IOException ioEx) {
                log.error("IOException in run method", ioEx);
            } finally {
                try {
                    serverSocket.close();
                } catch (IOException ioEx) {
                    log.error("Exception encountered closing server socket", ioEx);
                }
            }
            log.info("Finished processing connection");
        }
    };
    acceptThread.start();
    clientSocket = new Socket();
    clientSocket.setSoTimeout(1000);
    clientSocket.connect(serverSocket.getLocalSocketAddress(), 10000);
    clientSocket.setTcpNoDelay(true);
    log.info("Begining message send loop ");
    byte[] message = "Hello World".getBytes();
    BufferedReader reader;
    for (int i = 1; i <= messageCount; ++i) {
        reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        OutputStream writer = clientSocket.getOutputStream();
        log.info("Sending payload");
        writer.write(message, 0, message.length);
        writer.flush();
        log.info("Sending terminator");
        writer.write('\n');
        writer.flush();
        log.info("Received Response #{}: {}", i, reader.readLine());
        Thread.sleep(1000);
    }
    log.info("Message send loop complete - closing connection");
    // Javadoc for Socket says closing the InputStream will close the connection
    clientSocket.getInputStream().close();
    if (!clientSocket.isClosed()) {
        log.warn("Closing input stream didn't close socket");
        clientSocket.close();
    }
    log.info("Sleeping ...");
    Thread.sleep(5000);
}
Also used : InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) IOException(java.io.IOException) Logger(org.slf4j.Logger) IOException(java.io.IOException) SocketTimeoutException(java.net.SocketTimeoutException) SocketTimeoutException(java.net.SocketTimeoutException) BufferedReader(java.io.BufferedReader) Socket(java.net.Socket) ServerSocket(java.net.ServerSocket) Test(org.junit.Test)

Aggregations

OutputStream (java.io.OutputStream)3717 IOException (java.io.IOException)1470 FileOutputStream (java.io.FileOutputStream)1192 InputStream (java.io.InputStream)1171 File (java.io.File)808 ByteArrayOutputStream (java.io.ByteArrayOutputStream)751 Test (org.junit.Test)681 BufferedOutputStream (java.io.BufferedOutputStream)418 FileInputStream (java.io.FileInputStream)380 Socket (java.net.Socket)362 ByteArrayInputStream (java.io.ByteArrayInputStream)201 OutputStreamWriter (java.io.OutputStreamWriter)201 URL (java.net.URL)193 HttpURLConnection (java.net.HttpURLConnection)162 BufferedInputStream (java.io.BufferedInputStream)151 InputStreamReader (java.io.InputStreamReader)149 FileNotFoundException (java.io.FileNotFoundException)143 Path (org.apache.hadoop.fs.Path)143 Path (java.nio.file.Path)138 BufferedReader (java.io.BufferedReader)133