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
}
}
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();
}
}
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();
}
}
}
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);
}
}
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;
}
Aggregations