List of usage examples for java.nio ByteBuffer flip
public final Buffer flip()
From source file:org.jboss.pnc.buildagent.client.BuildAgentClient.java
private ByteBuffer prepareRemoteCommand(Object command) throws BuildAgentClientException { Map<String, Object> cmdJson = new HashMap<>(); cmdJson.put("action", "read"); ByteBuffer byteBuffer; if (command instanceof String) { cmdJson.put("data", command + "\n"); ObjectMapper mapper = new ObjectMapper(); try {//from w w w . j a va 2 s . com byteBuffer = ByteBuffer.wrap(mapper.writeValueAsBytes(cmdJson)); } catch (JsonProcessingException e) { throw new BuildAgentClientException("Cannot serialize string command.", e); } } else { try { byteBuffer = ByteBuffer.allocate(1).put(((Integer) command).byteValue()); } catch (BufferOverflowException | ClassCastException e) { throw new BuildAgentClientException("Invalid signal.", e); } byteBuffer.flip(); } return byteBuffer; }
From source file:dk.statsbiblioteket.util.LineReaderTest.java
public void testNIO() throws Exception { byte[] INITIAL = new byte[] { 1, 2, 3, 4 }; byte[] EXTRA = new byte[] { 5, 6, 7, 8 }; byte[] FULL = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; byte[] FIFTH = new byte[] { 87 }; byte[] FULL_WITH_FIFTH = new byte[] { 1, 2, 3, 4, 87, 6, 7, 8 }; // Create temp-file with content File temp = createTempFile(); FileOutputStream fileOut = new FileOutputStream(temp, true); fileOut.write(INITIAL);/*from w w w . ja v a 2 s .co m*/ fileOut.close(); checkContent("The plain test-file should be correct", temp, INITIAL); { // Read the 4 bytes RandomAccessFile input = new RandomAccessFile(temp, "r"); FileChannel channelIn = input.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(4096); channelIn.position(0); assertEquals("Buffer read should read full length", INITIAL.length, channelIn.read(buffer)); buffer.position(0); checkContent("Using buffer should produce the right bytes", INITIAL, buffer); channelIn.close(); input.close(); } { // Fill new buffer ByteBuffer outBuffer = ByteBuffer.allocate(4096); outBuffer.put(EXTRA); outBuffer.flip(); assertEquals("The limit of the outBuffer should be correct", EXTRA.length, outBuffer.limit()); // Append new buffer to end RandomAccessFile output = new RandomAccessFile(temp, "rw"); FileChannel channelOut = output.getChannel(); channelOut.position(INITIAL.length); assertEquals("All bytes should be written", EXTRA.length, channelOut.write(outBuffer)); channelOut.close(); output.close(); checkContent("The resulting file should have the full output", temp, FULL); } { // Fill single byte buffer ByteBuffer outBuffer2 = ByteBuffer.allocate(4096); outBuffer2.put(FIFTH); outBuffer2.flip(); assertEquals("The limit of the second outBuffer should be correct", FIFTH.length, outBuffer2.limit()); // Insert byte in the middle RandomAccessFile output2 = new RandomAccessFile(temp, "rw"); FileChannel channelOut2 = output2.getChannel(); channelOut2.position(4); assertEquals("The FIFTH should be written", FIFTH.length, channelOut2.write(outBuffer2)); channelOut2.close(); output2.close(); checkContent("The resulting file with fifth should be complete", temp, FULL_WITH_FIFTH); } }
From source file:org.commonjava.indy.httprox.handler.ProxyRequestReader.java
private int doRead(final ConduitStreamSourceChannel channel) throws IOException { bReq = new ByteArrayOutputStream(); pReq = new PrintStream(bReq); logger.debug("Starting read: {}", channel); int total = 0; while (true) { ByteBuffer buf = ByteBuffer.allocate(1024); channel.awaitReadable(AWAIT_READABLE_IN_MILLISECONDS, TimeUnit.MILLISECONDS); int read = channel.read(buf); // return the number of bytes read, possibly zero, or -1 logger.debug("Read {} bytes", read); if (read == -1) // return -1 if the channel has reached end-of-stream {/*w w w .ja va 2 s . co m*/ if (total == 0) // nothing read, return -1 to indicate the EOF { return -1; } else { return total; } } if (read == 0) // no new bytes this time { return total; } total += read; buf.flip(); byte[] bbuf = new byte[buf.limit()]; buf.get(bbuf); if (!headDone) { // allows us to stop after header read... final String part = new String(bbuf); for (final char c : part.toCharArray()) { switch (c) { case '\n': { while (lastFour.size() > 3) { lastFour.remove(0); } lastFour.add(c); try { if (bReq.size() > 0 && HEAD_END.equals(lastFour)) { logger.debug("Detected end of request headers."); headDone = true; logger.trace("Proxy request header:\n{}\n", new String(bReq.toByteArray())); } } finally { lastFour.remove(lastFour.size() - 1); } } default: { pReq.print(c); lastFour.add(c); } } } } else { bReq.write(bbuf); } } }
From source file:gda.device.scannable.keyence.Keyence.java
/** * Send command to the server./*from w w w . ja v a 2 s. c om*/ * * @param msg * an unterminated command * @param expectedReplyItems * @return the reply string. * @throws DeviceException */ public Object[] processImageRequest(String msg, int expectedReplyItems) throws DeviceException { if (expectedReplyItems < 2) throw new IllegalArgumentException("need at least two values for images (length definition and data)"); String command = msg + '\r'; Object reply[] = new Object[expectedReplyItems + 1]; logger.debug(getName() + ": sent command: " + msg); synchronized (socketAccessLock) { try { if (!isConnected()) { throw new DeviceException("not connected"); } cleanPipe(); socketChannel.write(encoder.encode(CharBuffer.wrap(command))); ByteBuffer singleByte = ByteBuffer.allocate(1); StringBuilder sb = new StringBuilder(); int argCounter = 0; while (argCounter < expectedReplyItems) { singleByte.clear(); socketChannel.socket().setSoTimeout(socketTimeOut); socketChannel.configureBlocking(true); while (singleByte.position() == 0) socketChannel.read(singleByte); singleByte.flip(); String c = decoder.decode(singleByte).toString(); logger.debug(c.toString()); if (c.equals(",")) { reply[argCounter] = sb.toString(); sb = new StringBuilder(); argCounter++; } else if (c.equals("\r")) { throw new DeviceException( "sendCommand: not enough data for image received - suspect an error"); } else { sb.append(c); } } int imageLength = Integer.parseInt(reply[expectedReplyItems - 1].toString()); byte[] imageData = new byte[imageLength]; ByteBuffer bybu = ByteBuffer.wrap(imageData); while (bybu.remaining() != 0) { socketChannel.read(bybu); } reply[expectedReplyItems] = imageData; } catch (SocketTimeoutException ex) { throw new DeviceException("sendCommand read timeout " + ex.getMessage(), ex); } catch (IOException ex) { // treat as fatal connected = false; throw new DeviceException("sendCommand: " + ex.getMessage(), ex); } } return reply; }
From source file:byps.BTransport.java
public void negotiateProtocolClient(final BAsyncResult<Boolean> asyncResult) { if (log.isDebugEnabled()) log.debug("negotiateProtocolClient("); if (log.isDebugEnabled()) log.debug("negotiateActive=" + negotiateActive); // Check that we do not run into recursive authentication requests. // Observed in production environments: negotateActive==true and no authentication request active // The reason for this problem might be that I did not set negotiateActive=false and asyncResultsWaitingForAuthentication.clear() in the same synchronized block. // To make authentication more stable, the number of outstanding authentication requests are checked. // If there are no authentication requests active, the flag negotiateActive is reset. synchronized (asyncResultsWaitingForAuthentication) { // Already have an active negotiation request? if (negotiateActive) { // Are there threads waiting? if (asyncResultsWaitingForAuthentication.size() != 0) { // Most likely slow or recursive authentication BException ex = new BException(BExceptionC.FORBIDDEN, "Authentication procedure failed. Server returned 401 for every request. " + "A common reason for this error is slow authentication handling."); // ... or calling a function that requires authentication in BAuthentication.authenticate() - see. TestRemoteWithAuthentication.testAuthenticateBlocksRecursion asyncResult.setAsyncResult(false, ex); return; } else { // Correction: if no threads are waiting then there cannot be an aktive negotiation request. negotiateActive = false; }/*from w w w. ja v a 2 s. c om*/ } else { // Now, this is the active negotiation request. negotiateActive = true; } } try { if (log.isDebugEnabled()) log.debug("build nego message"); ByteBuffer buf = ByteBuffer.allocate(BNegotiate.NEGOTIATE_MAX_SIZE); final BNegotiate negoRequest = new BNegotiate(apiDesc); negoRequest.write(buf); buf.flip(); BAsyncResult<BMessage> outerResult = new BAsyncResult<BMessage>() { @Override public void setAsyncResult(BMessage msg, Throwable e) { try { if (log.isDebugEnabled()) log.debug("nego result=" + msg + ", ex=" + e); if (e == null) { BNegotiate negoResponse = null; if (msg.header.messageObject != null) { negoResponse = (BNegotiate) msg.header.messageObject; } else { negoResponse = new BNegotiate(); negoResponse.read(msg.buf); } applyNegotiate(negoResponse); internalAuthenticate(asyncResult); } else { asyncResult.setAsyncResult(Boolean.FALSE, e); } } catch (Throwable ex) { asyncResult.setAsyncResult(Boolean.FALSE, ex); } } }; if (log.isDebugEnabled()) log.debug("send nego"); BMessageHeader header = new BMessageHeader(); header.messageId = wire.makeMessageId(); final BMessage msg = new BMessage(header, buf, null); wire.send(msg, outerResult); } catch (Throwable e) { if (log.isDebugEnabled()) log.debug("nego failed, ", e); asyncResult.setAsyncResult(Boolean.FALSE, e); } if (log.isDebugEnabled()) log.debug(")negotiateProtocolClient"); }
From source file:org.apache.hadoop.oncrpc.TestFrameDecoder.java
@Test public void testSingleFrame() { RpcFrameDecoder decoder = new RpcFrameDecoder(); // Test "Length field is not received yet" ByteBuffer buffer = ByteBuffer.allocate(1); ChannelBuffer buf = new ByteBufferBackedChannelBuffer(buffer); ChannelBuffer channelBuffer = (ChannelBuffer) decoder.decode(Mockito.mock(ChannelHandlerContext.class), Mockito.mock(Channel.class), buf); assertTrue(channelBuffer == null);/*from ww w .ja v a 2s . c om*/ // Test all bytes are not received yet byte[] fragment = new byte[4 + 9]; fragment[0] = (byte) (1 << 7); // final fragment fragment[1] = 0; fragment[2] = 0; fragment[3] = (byte) 10; // fragment size = 10 bytes assertTrue(XDR.isLastFragment(fragment)); assertTrue(XDR.fragmentSize(fragment) == 10); buffer = ByteBuffer.allocate(4 + 9); buffer.put(fragment); buffer.flip(); buf = new ByteBufferBackedChannelBuffer(buffer); channelBuffer = (ChannelBuffer) decoder.decode(Mockito.mock(ChannelHandlerContext.class), Mockito.mock(Channel.class), buf); assertTrue(channelBuffer == null); }
From source file:Proxy.java
/** * Read all data from <code>from</code> and write it to <code>to</code>. * Returns false if channel was closed/* w w w .ja v a 2s . co m*/ */ boolean relay(SocketChannel from, SocketChannel to, ByteBuffer buf) throws Exception { int num; StringBuilder sb; buf.clear(); while (true) { num = from.read(buf); if (num < 0) return false; else if (num == 0) return true; buf.flip(); if (verbose) { log(printRelayedData(toString(from), toString(to), buf.remaining())); } if (debug) { sb = new StringBuilder(); sb.append(new String(buf.array()).trim()); sb.append('\n'); log(sb.toString()); } to.write(buf); buf.flip(); } }
From source file:net.jenet.Host.java
/** * @param buffer/*from w w w. j a va2 s . c o m*/ * @return */ int receive(ByteBuffer buffer) { try { buffer.clear(); receivedAddress = (InetSocketAddress) communicationChannel.receive(buffer); buffer.flip(); if (receivedAddress != null) LOG.debug("Host.receive:" + address + ". Received " + buffer.limit() + " bytes from " + receivedAddress); return buffer.limit(); } catch (Exception e) { LOG.error("Host.receive: Error reading buffers.", e); return -1; } }
From source file:com.carreygroup.JARVIS.Demon.java
public boolean Send(Packet p) throws IOException { boolean ret = false; if ((Ethnet_Mode == Ethnet.TCP) || (Ethnet_Mode == Ethnet.P2P)) { ByteBuffer bytebufOut = ByteBuffer.allocate(Ethnet.BUFFER_SIZE); bytebufOut = ByteBuffer.wrap(p.toByteArray()); try {/* ww w.j a v a2 s .c o m*/ mPrintWriterClient.print(new String(bytebufOut.array()));// mPrintWriterClient.flush(); ret = true; } catch (Exception e) { notifyDisconnected(); throw new IOException(""); } bytebufOut.flip(); bytebufOut.clear(); } if (Ethnet_Mode == Ethnet.UDP) { byte[] buff = p.toByteArray(); DatagramPacket packet = new DatagramPacket(buff, buff.length, mAddress); mSendPSocket.send(packet);// ret = true; } return ret; }
From source file:org.alfresco.contentstore.ChecksumTest.java
private void assertEqual(InputStream expected, InputStream actual) throws IOException { ByteBuffer bb1 = ByteBuffer.allocate(1024); ByteBuffer bb2 = ByteBuffer.allocate(1024); try (ReadableByteChannel expectedChannel = Channels.newChannel(expected); ReadableByteChannel actualChannel = Channels.newChannel(actual)) { State state = new State(); for (;;) { int numRead1 = expectedChannel.read(bb1); bb1.flip(); int numRead2 = actualChannel.read(bb2); bb2.flip();// w ww . j ava 2 s . com assertEqual(bb1, bb2, state); if (numRead1 < 1) { break; } bb1.clear(); bb2.clear(); } } }