Search in sources :

Example 21 with ReadableByteChannel

use of java.nio.channels.ReadableByteChannel in project robovm by robovm.

the class ChannelsTest method testNewReaderReadableByteChannelString_InputNull.

/*
     * Test method for
     * 'java.nio.channels.Channels.newReader(ReadableByteChannel, String)'
     */
public void testNewReaderReadableByteChannelString_InputNull() throws IOException {
    int bufSize = this.testNum;
    int readres = 0;
    CharBuffer charBuf = CharBuffer.allocate(bufSize);
    this.fins = new FileInputStream(tmpFile);
    // channel null
    Reader testReader;
    try {
        testReader = Channels.newReader(null, Charset.forName(CODE_SET).newDecoder(), -1);
        assertNotNull(testReader);
        assertFalse(testReader.ready());
        readres = testReader.read((CharBuffer) null);
        fail();
    } catch (NullPointerException e) {
    // correct
    }
    assertEquals(0, readres);
    this.fins = null;
    // channel with null inputs
    try {
        ReadableByteChannel rbChannel = Channels.newChannel(this.fins);
        testReader = Channels.newReader(rbChannel, Charset.forName(CODE_SET).newDecoder(), -1);
        assertNotNull(testReader);
        assertFalse(testReader.ready());
        readres = testReader.read(charBuf);
        fail();
    } catch (NullPointerException e) {
    // correct
    }
}
Also used : ReadableByteChannel(java.nio.channels.ReadableByteChannel) CharBuffer(java.nio.CharBuffer) Reader(java.io.Reader) FileInputStream(java.io.FileInputStream)

Example 22 with ReadableByteChannel

use of java.nio.channels.ReadableByteChannel in project camel by apache.

the class EchoService method doPost.

public void doPost(HttpServletRequest request, HttpServletResponse response) {
    ByteBuffer bb;
    List<ByteBuffer> bbList = null;
    try {
        int bufKBytes = DEFAULT_BUFFER_SIZE;
        int delaySecs = 0;
        String soapAction = request.getHeader("SOAPAction");
        if (soapAction != null) {
            if (soapAction.startsWith("\"")) {
                soapAction = soapAction.replaceAll("\"", "");
            }
            int dotPos = soapAction.indexOf(".");
            int secondDotPos = dotPos == -1 ? -1 : soapAction.indexOf(".", dotPos + 1);
            if (secondDotPos > 0) {
                bufKBytes = Integer.parseInt(soapAction.substring(dotPos + 1, secondDotPos));
                delaySecs = Integer.parseInt(soapAction.substring(secondDotPos + 1));
            } else if (dotPos > 0) {
                bufKBytes = Integer.parseInt(soapAction.substring(dotPos + 1));
            }
        }
        bb = ByteBuffer.allocate(bufKBytes * 1024);
        ReadableByteChannel rbc = Channels.newChannel(request.getInputStream());
        int len = 0;
        int tot = 0;
        while ((len = rbc.read(bb)) > 0) {
            tot += len;
            if (tot >= bb.capacity()) {
                // --- auto expand logic ---
                if (bbList == null) {
                    bbList = new ArrayList<ByteBuffer>();
                }
                bb.flip();
                bbList.add(bb);
                bufKBytes = bufKBytes * 2;
                bb = ByteBuffer.allocate(bufKBytes * 1024);
            }
        }
        bb.flip();
        // sleep when a "sleep" header exists - but if "port" is also specified, only when it matches
        String sleep = request.getHeader("sleep");
        if (sleep != null) {
            String port = request.getHeader("port");
            if (port != null) {
                if (request.getLocalPort() == Integer.parseInt(port)) {
                    Long sleepVal = Long.parseLong(sleep);
                    System.out.println("Echo Service on port : " + port + " sleeping for : " + sleepVal);
                    Thread.sleep(sleepVal);
                }
            } else {
                Long sleepVal = Long.parseLong(sleep);
                System.out.println("Echo Service on port : " + request.getLocalPort() + " sleeping for : " + sleepVal);
                Thread.sleep(sleepVal);
            }
        }
        // --- auto expand logic ---
        if (bbList != null) {
            bbList.add(bb);
        }
        if (delaySecs > 0 && request.getLocalPort() == 9000) {
            // sleep only when running on port 9000
            Thread.sleep(delaySecs * 1000);
        } else if (delayMillis > 0) {
            Thread.sleep(delayMillis);
        }
        response.setContentType(request.getContentType());
        response.setHeader("port", Integer.toString(request.getLocalPort()));
        //System.out.println("Reply from Echo service on port : " + request.getLocalPort());
        OutputStream out = response.getOutputStream();
        WritableByteChannel wbc = Channels.newChannel(out);
        if (bbList == null) {
            do {
                len = wbc.write(bb);
            } while (len > 0);
        } else {
            // --- auto expand logic ---
            for (ByteBuffer b : bbList) {
                do {
                    len = wbc.write(b);
                } while (len > 0);
            }
        }
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : ReadableByteChannel(java.nio.channels.ReadableByteChannel) OutputStream(java.io.OutputStream) WritableByteChannel(java.nio.channels.WritableByteChannel) ByteBuffer(java.nio.ByteBuffer)

Example 23 with ReadableByteChannel

use of java.nio.channels.ReadableByteChannel in project camel by apache.

the class DefaultUndertowHttpBinding method readFromChannel.

byte[] readFromChannel(StreamSourceChannel source) throws IOException {
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final ByteBuffer buffer = ByteBuffer.wrap(new byte[1024]);
    ReadableByteChannel blockingSource = new BlockingReadableByteChannel(source);
    for (; ; ) {
        int res = blockingSource.read(buffer);
        if (res == -1) {
            return out.toByteArray();
        } else if (res == 0) {
            LOG.error("Channel did not block");
        } else {
            buffer.flip();
            out.write(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.arrayOffset() + buffer.limit());
            buffer.clear();
        }
    }
}
Also used : BlockingReadableByteChannel(org.xnio.channels.BlockingReadableByteChannel) BlockingReadableByteChannel(org.xnio.channels.BlockingReadableByteChannel) ReadableByteChannel(java.nio.channels.ReadableByteChannel) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ByteBuffer(java.nio.ByteBuffer)

Example 24 with ReadableByteChannel

use of java.nio.channels.ReadableByteChannel in project cassandra by apache.

the class IncomingTcpConnection method receiveMessages.

// Not closing constructed DataInputPlus's as the stream needs to remain open.
@SuppressWarnings("resource")
private void receiveMessages() throws IOException {
    // handshake (true) endpoint versions
    DataOutputStream out = new DataOutputStream(socket.getOutputStream());
    // if this version is < the MS version the other node is trying
    // to connect with, the other node will disconnect
    out.writeInt(MessagingService.current_version);
    out.flush();
    DataInputPlus in = new DataInputStreamPlus(socket.getInputStream());
    int maxVersion = in.readInt();
    // outbound side will reconnect if necessary to upgrade version
    assert version <= MessagingService.current_version;
    from = CompactEndpointSerializationHelper.deserialize(in);
    // record the (true) version of the endpoint
    MessagingService.instance().setVersion(from, maxVersion);
    logger.trace("Set version for {} to {} (will use {})", from, maxVersion, MessagingService.instance().getVersion(from));
    if (compressed) {
        logger.trace("Upgrading incoming connection to be compressed");
        LZ4FastDecompressor decompressor = LZ4Factory.fastestInstance().fastDecompressor();
        Checksum checksum = XXHashFactory.fastestInstance().newStreamingHash32(OutboundTcpConnection.LZ4_HASH_SEED).asChecksum();
        in = new DataInputStreamPlus(new LZ4BlockInputStream(socket.getInputStream(), decompressor, checksum));
    } else {
        ReadableByteChannel channel = socket.getChannel();
        in = new NIODataInputStream(channel != null ? channel : Channels.newChannel(socket.getInputStream()), BUFFER_SIZE);
    }
    while (true) {
        MessagingService.validateMagic(in.readInt());
        receiveMessage(in, version);
    }
}
Also used : ReadableByteChannel(java.nio.channels.ReadableByteChannel) LZ4FastDecompressor(net.jpountz.lz4.LZ4FastDecompressor) Checksum(java.util.zip.Checksum) DataInputStreamPlus(org.apache.cassandra.io.util.DataInputPlus.DataInputStreamPlus) DataInputPlus(org.apache.cassandra.io.util.DataInputPlus) LZ4BlockInputStream(net.jpountz.lz4.LZ4BlockInputStream) NIODataInputStream(org.apache.cassandra.io.util.NIODataInputStream)

Example 25 with ReadableByteChannel

use of java.nio.channels.ReadableByteChannel in project camel by apache.

the class ObjectHelper method getScanner.

/**
     * Creates a {@link Scanner} for scanning the given value.
     *
     * @param exchange  the current exchange
     * @param value     the value, typically the message IN body
     * @return the scanner, is newer <tt>null</tt>
     */
public static Scanner getScanner(Exchange exchange, Object value) {
    if (value instanceof WrappedFile) {
        WrappedFile<?> gf = (WrappedFile<?>) value;
        Object body = gf.getBody();
        if (body != null) {
            // we have loaded the file content into the body so use that
            value = body;
        } else {
            // generic file is just a wrapper for the real file so call again with the real file
            return getScanner(exchange, gf.getFile());
        }
    }
    String charset = exchange.getProperty(Exchange.CHARSET_NAME, String.class);
    Scanner scanner = null;
    if (value instanceof Readable) {
        scanner = new Scanner((Readable) value);
    } else if (value instanceof InputStream) {
        scanner = charset == null ? new Scanner((InputStream) value) : new Scanner((InputStream) value, charset);
    } else if (value instanceof File) {
        try {
            scanner = charset == null ? new Scanner((File) value) : new Scanner((File) value, charset);
        } catch (FileNotFoundException e) {
            throw new RuntimeCamelException(e);
        }
    } else if (value instanceof String) {
        scanner = new Scanner((String) value);
    } else if (value instanceof ReadableByteChannel) {
        scanner = charset == null ? new Scanner((ReadableByteChannel) value) : new Scanner((ReadableByteChannel) value, charset);
    }
    if (scanner == null) {
        // value is not a suitable type, try to convert value to a string
        String text = exchange.getContext().getTypeConverter().convertTo(String.class, exchange, value);
        if (text != null) {
            scanner = new Scanner(text);
        }
    }
    if (scanner == null) {
        scanner = new Scanner("");
    }
    return scanner;
}
Also used : Scanner(java.util.Scanner) ReadableByteChannel(java.nio.channels.ReadableByteChannel) WrappedFile(org.apache.camel.WrappedFile) InputStream(java.io.InputStream) FileNotFoundException(java.io.FileNotFoundException) RuntimeCamelException(org.apache.camel.RuntimeCamelException) File(java.io.File) WrappedFile(org.apache.camel.WrappedFile)

Aggregations

ReadableByteChannel (java.nio.channels.ReadableByteChannel)307 ByteBuffer (java.nio.ByteBuffer)111 IOException (java.io.IOException)84 FileOutputStream (java.io.FileOutputStream)62 WritableByteChannel (java.nio.channels.WritableByteChannel)62 Test (org.junit.Test)52 File (java.io.File)50 FileChannel (java.nio.channels.FileChannel)49 FileInputStream (java.io.FileInputStream)43 ByteArrayInputStream (java.io.ByteArrayInputStream)38 InputStream (java.io.InputStream)36 URL (java.net.URL)35 ByteArrayOutputStream (java.io.ByteArrayOutputStream)21 Path (java.nio.file.Path)18 Test (org.testng.annotations.Test)14 FileNotFoundException (java.io.FileNotFoundException)13 ArrayList (java.util.ArrayList)12 DbusEventGenerator (com.linkedin.databus.core.test.DbusEventGenerator)11 MalformedURLException (java.net.MalformedURLException)11 Vector (java.util.Vector)11