List of usage examples for java.nio ByteBuffer reset
public final Buffer reset()
mark
. From source file:org.apache.nifi.processor.util.listen.handler.socket.StandardSocketChannelHandler.java
@Override public void run() { boolean eof = false; SocketChannel socketChannel = null; try {/* w ww.ja v a 2 s . co m*/ int bytesRead; socketChannel = (SocketChannel) key.channel(); final SocketChannelAttachment attachment = (SocketChannelAttachment) key.attachment(); final ByteBuffer socketBuffer = attachment.getByteBuffer(); // read until the buffer is full while ((bytesRead = socketChannel.read(socketBuffer)) > 0) { // prepare byte buffer for reading socketBuffer.flip(); // mark the current position as start, in case of partial message read socketBuffer.mark(); // process the contents that have been read into the buffer processBuffer(socketChannel, socketBuffer); // Preserve bytes in buffer for next call to run // NOTE: This code could benefit from the two ByteBuffer read calls to avoid // this compact for higher throughput socketBuffer.reset(); socketBuffer.compact(); logger.debug("bytes read {}", new Object[] { bytesRead }); } // Check for closed socket if (bytesRead < 0) { eof = true; logger.debug("Reached EOF, closing connection"); } else { logger.debug("No more data available, returning for selection"); } } catch (ClosedByInterruptException | InterruptedException e) { logger.debug("read loop interrupted, closing connection"); // Treat same as closed socket eof = true; } catch (ClosedChannelException e) { // ClosedChannelException doesn't have a message so handle it separately from IOException logger.error("Error reading from channel due to channel being closed", e); // Treat same as closed socket eof = true; } catch (IOException e) { logger.error("Error reading from channel due to {}", new Object[] { e.getMessage() }, e); // Treat same as closed socket eof = true; } finally { if (eof == true) { IOUtils.closeQuietly(socketChannel); dispatcher.completeConnection(key); } else { dispatcher.addBackForSelection(key); } } }
From source file:org.apache.jackrabbit.oak.plugins.segment.file.TarReader.java
/** * Loads the optional pre-compiled graph entry from the given tar file. * * @return graph buffer, or {@code null} if one was not found * @throws IOException if the tar file could not be read *//* w ww . j a v a 2 s . c o m*/ private ByteBuffer loadGraph() throws IOException { // read the graph metadata just before the tar index entry int pos = access.length() - 2 * BLOCK_SIZE - getEntrySize(index.remaining()); ByteBuffer meta = access.read(pos - 16, 16); int crc32 = meta.getInt(); int count = meta.getInt(); int bytes = meta.getInt(); int magic = meta.getInt(); if (magic != GRAPH_MAGIC) { return null; // magic byte mismatch } if (count < 0 || bytes < count * 16 + 16 || BLOCK_SIZE + bytes > pos) { log.warn("Invalid graph metadata in tar file {}", file); return null; // impossible uuid and/or byte counts } // this involves seeking backwards in the file, which might not // perform well, but that's OK since we only do this once per file ByteBuffer graph = access.read(pos - bytes, bytes); byte[] b = new byte[bytes - 16]; graph.mark(); graph.get(b); graph.reset(); CRC32 checksum = new CRC32(); checksum.update(b); if (crc32 != (int) checksum.getValue()) { log.warn("Invalid graph checksum in tar file {}", file); return null; // checksum mismatch } return graph; }
From source file:org.apache.jackrabbit.oak.segment.file.TarReader.java
/** * Loads the optional pre-compiled graph entry from the given tar file. * * @return graph buffer, or {@code null} if one was not found * @throws IOException if the tar file could not be read *///from www. j a v a2 s . c o m private ByteBuffer loadGraph() throws IOException { // read the graph metadata just before the tar index entry int pos = access.length() - 2 * BLOCK_SIZE - getEntrySize(index.remaining() + 16); ByteBuffer meta = access.read(pos - 16, 16); int crc32 = meta.getInt(); int count = meta.getInt(); int bytes = meta.getInt(); int magic = meta.getInt(); if (magic != GRAPH_MAGIC) { return null; // magic byte mismatch } if (count < 0 || bytes < count * 16 + 16 || BLOCK_SIZE + bytes > pos) { log.warn("Invalid graph metadata in tar file {}", file); return null; // impossible uuid and/or byte counts } // this involves seeking backwards in the file, which might not // perform well, but that's OK since we only do this once per file ByteBuffer graph = access.read(pos - bytes, bytes); byte[] b = new byte[bytes - 16]; graph.mark(); graph.get(b); graph.reset(); CRC32 checksum = new CRC32(); checksum.update(b); if (crc32 != (int) checksum.getValue()) { log.warn("Invalid graph checksum in tar file {}", file); return null; // checksum mismatch } hasGraph = true; return graph; }
From source file:io.Text.java
/** * Finds any occurence of <code>what</code> in the backing * buffer, starting as position <code>start</code>. The starting * position is measured in bytes and the return value is in * terms of byte position in the buffer. The backing buffer is * not converted to a string for this operation. * @return byte position of the first occurence of the search * string in the UTF-8 buffer or -1 if not found *//*ww w. ja va 2 s . c o m*/ public int find(String what, int start) { try { ByteBuffer src = ByteBuffer.wrap(this.bytes, 0, this.length); ByteBuffer tgt = encode(what); byte b = tgt.get(); src.position(start); while (src.hasRemaining()) { if (b == src.get()) { // matching first byte src.mark(); // save position in loop tgt.mark(); // save position in target boolean found = true; int pos = src.position() - 1; while (tgt.hasRemaining()) { if (!src.hasRemaining()) { // src expired first tgt.reset(); src.reset(); found = false; break; } if (!(tgt.get() == src.get())) { tgt.reset(); src.reset(); found = false; break; // no match } } if (found) return pos; } } return -1; // not found } catch (CharacterCodingException e) { // can't get here e.printStackTrace(); return -1; } }
From source file:org.cloudata.core.common.io.CText.java
/** * Finds any occurence of <code>what</code> in the backing * buffer, starting as position <code>start</code>. The starting * position is measured in bytes and the return value is in * terms of byte position in the buffer. The backing buffer is * not converted to a string for this operation. * @return byte position of the first occurence of the search * string in the UTF-8 buffer or -1 if not found *//* ww w.jav a 2 s. c o m*/ public int find(String what, int start) { try { ByteBuffer src = ByteBuffer.wrap(this.bytes); ByteBuffer tgt = encode(what); byte b = tgt.get(); src.position(start); while (src.hasRemaining()) { if (b == src.get()) { // matching first byte src.mark(); // save position in loop tgt.mark(); // save position in target boolean found = true; int pos = src.position() - 1; while (tgt.hasRemaining()) { if (!src.hasRemaining()) { // src expired first tgt.reset(); src.reset(); found = false; break; } if (!(tgt.get() == src.get())) { tgt.reset(); src.reset(); found = false; break; // no match } } if (found) return pos; } } return -1; // not found } catch (CharacterCodingException e) { // can't get here e.printStackTrace(); return -1; } }
From source file:org.apache.arrow.vector.util.Text.java
/** * Finds any occurence of <code>what</code> in the backing buffer, starting as position <code>start</code>. The * starting position is measured in bytes and the return value is in terms of byte position in the buffer. The backing * buffer is not converted to a string for this operation. * * @return byte position of the first occurence of the search string in the UTF-8 buffer or -1 if not found *///ww w .j a v a2s.com public int find(String what, int start) { try { ByteBuffer src = ByteBuffer.wrap(this.bytes, 0, this.length); ByteBuffer tgt = encode(what); byte b = tgt.get(); src.position(start); while (src.hasRemaining()) { if (b == src.get()) { // matching first byte src.mark(); // save position in loop tgt.mark(); // save position in target boolean found = true; int pos = src.position() - 1; while (tgt.hasRemaining()) { if (!src.hasRemaining()) { // src expired first tgt.reset(); src.reset(); found = false; break; } if (!(tgt.get() == src.get())) { tgt.reset(); src.reset(); found = false; break; // no match } } if (found) { return pos; } } } return -1; // not found } catch (CharacterCodingException e) { // can't get here e.printStackTrace(); return -1; } }
From source file:com.offbynull.portmapper.natpmp.NatPmpController.java
/** * Constructs a {@link NatPmpController} object. * @param gatewayAddress address of router/gateway * @param listener a listener to listen for all NAT-PMP packets from this router * @throws NullPointerException if any argument is {@code null} * @throws IOException if problems initializing UDP channels *///w ww.j a v a 2 s. c om public NatPmpController(InetAddress gatewayAddress, final NatPmpControllerListener listener) throws IOException { Validate.notNull(gatewayAddress); this.gateway = new InetSocketAddress(gatewayAddress, 5351); List<DatagramChannel> channels = new ArrayList<>(3); try { unicastChannel = DatagramChannel.open(); unicastChannel.configureBlocking(false); unicastChannel.socket().bind(new InetSocketAddress(0)); ipv4MulticastChannel = DatagramChannel.open(StandardProtocolFamily.INET); ipv4MulticastChannel.configureBlocking(false); ipv4MulticastChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true); ipv4MulticastChannel.socket().bind(new InetSocketAddress(5350)); NetworkUtils.multicastListenOnAllIpv4InterfaceAddresses(ipv4MulticastChannel); ipv6MulticastChannel = DatagramChannel.open(StandardProtocolFamily.INET6); ipv6MulticastChannel.configureBlocking(false); ipv6MulticastChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true); ipv6MulticastChannel.socket().bind(new InetSocketAddress(5350)); NetworkUtils.multicastListenOnAllIpv6InterfaceAddresses(ipv6MulticastChannel); } catch (IOException ioe) { IOUtils.closeQuietly(unicastChannel); IOUtils.closeQuietly(ipv4MulticastChannel); IOUtils.closeQuietly(ipv6MulticastChannel); throw ioe; } channels.add(unicastChannel); channels.add(ipv4MulticastChannel); channels.add(ipv6MulticastChannel); this.communicator = new UdpCommunicator(channels); this.communicator.startAsync().awaitRunning(); if (listener != null) { this.communicator.addListener(new UdpCommunicatorListener() { @Override public void incomingPacket(InetSocketAddress sourceAddress, DatagramChannel channel, ByteBuffer packet) { CommunicationType type; if (channel == unicastChannel) { type = CommunicationType.UNICAST; } else if (channel == ipv4MulticastChannel || channel == ipv6MulticastChannel) { type = CommunicationType.MULTICAST; } else { return; // unknown, do nothing } try { packet.mark(); listener.incomingResponse(type, new ExternalAddressNatPmpResponse(packet)); } catch (BufferUnderflowException | IllegalArgumentException e) { // NOPMD // ignore } finally { packet.reset(); } try { packet.mark(); listener.incomingResponse(type, new UdpMappingNatPmpResponse(packet)); } catch (BufferUnderflowException | IllegalArgumentException e) { // NOPMD // ignore } finally { packet.reset(); } try { packet.mark(); listener.incomingResponse(type, new TcpMappingNatPmpResponse(packet)); } catch (BufferUnderflowException | IllegalArgumentException e) { // NOPMD // ignore } finally { packet.reset(); } } }); } }
From source file:net.ymate.platform.serv.nio.datagram.NioUdpServer.java
public synchronized void start() throws IOException { if (!__isStarted) { __isStarted = true;//from w w w . j av a2 s . c o m __eventGroup = new NioEventGroup<NioUdpListener>(__serverCfg, __listener, __codec) { @Override protected SelectableChannel __doChannelCreate(INioServerCfg cfg) throws IOException { DatagramChannel _channel = DatagramChannel.open(); _channel.configureBlocking(false); _channel.socket().bind(new InetSocketAddress(cfg.getServerHost(), cfg.getPort())); return _channel; } @Override protected String __doBuildProcessorName() { return StringUtils.capitalize(name()).concat("UdpServer-NioEventProcessor-"); } @Override protected void __doInitProcessors() throws IOException { __processors = new NioEventProcessor[__selectorCount]; for (int _idx = 0; _idx < __selectorCount; _idx++) { __processors[_idx] = new NioEventProcessor<NioUdpListener>(this, __doBuildProcessorName() + _idx) { @Override protected void __doExceptionEvent(SelectionKey key, final Throwable e) { final INioSession _session = (INioSession) key.attachment(); if (_session != null) { __eventGroup.executorService().submit(new Runnable() { public void run() { try { __eventGroup.listener().onExceptionCaught(e, _session); } catch (Throwable ex) { _LOG.error(e.getMessage(), RuntimeUtils.unwrapThrow(ex)); } } }); } else { _LOG.error(e.getMessage(), RuntimeUtils.unwrapThrow(e)); } } }; __processors[_idx].start(); } } @Override protected void __doRegisterEvent() throws IOException { for (NioEventProcessor _processor : __processors) { _processor.registerEvent(__channel, SelectionKey.OP_READ, new NioSession<NioUdpListener>(this, __channel) { @Override protected int __doChannelRead(ByteBuffer buffer) throws IOException { SocketAddress _address = ((DatagramChannel) __channel).receive(buffer); if (_address != null) { attr(SocketAddress.class.getName(), _address); return __buffer.remaining(); } return 0; } @Override protected int __doChannelWrite(ByteBuffer buffer) throws IOException { SocketAddress _address = attr(SocketAddress.class.getName()); if (_address != null) { return ((DatagramChannel) __channel).send(buffer, _address); } buffer.reset(); return 0; } }); } } }; __eventGroup.start(); // _LOG.info("UdpServer [" + __eventGroup.name() + "] started at " + __serverCfg.getServerHost() + ":" + __serverCfg.getPort()); } }
From source file:org.commoncrawl.util.TextBytes.java
/** * Finds any occurence of <code>what</code> in the backing buffer, starting as * position <code>start</code>. The starting position is measured in bytes and * the return value is in terms of byte position in the buffer. The backing * buffer is not converted to a string for this operation. * //from w w w.ja v a 2s . c om * @return byte position of the first occurence of the search string in the * UTF-8 buffer or -1 if not found */ public int find(String what, int start) { try { ByteBuffer src = ByteBuffer.wrap(bytes.get(), bytes.getOffset(), bytes.getCount()); ByteBuffer tgt = encode(what); byte b = tgt.get(); src.position(start); while (src.hasRemaining()) { if (b == src.get()) { // matching first byte src.mark(); // save position in loop tgt.mark(); // save position in target boolean found = true; int pos = src.position() - 1; while (tgt.hasRemaining()) { if (!src.hasRemaining()) { // src expired first tgt.reset(); src.reset(); found = false; break; } if (!(tgt.get() == src.get())) { tgt.reset(); src.reset(); found = false; break; // no match } } if (found) return pos; } } return -1; // not found } catch (CharacterCodingException e) { // can't get here e.printStackTrace(); return -1; } }
From source file:byps.http.HWireClient.java
protected RequestToCancel createRequestForMessage(BMessage msg, BAsyncResult<BMessage> asyncResult, int timeoutSecondsRequest) { if (log.isDebugEnabled()) log.debug("createRequestForMessage(" + msg); ByteBuffer requestDataBuffer = msg.buf; if (log.isDebugEnabled()) { requestDataBuffer.mark();// w ww . j ava2 s. c om BBufferJson bbuf = new BBufferJson(requestDataBuffer); log.debug(bbuf.toDetailString()); requestDataBuffer.reset(); } final RequestToCancel requestToCancel = new RequestToCancel(msg.header.messageId, 0L, 0L, asyncResult); final boolean isNegotiate = BNegotiate.isNegotiateMessage(requestDataBuffer); final boolean isJson = isNegotiate || BMessageHeader.detectProtocol(requestDataBuffer) == BMessageHeader.MAGIC_JSON; if (log.isDebugEnabled()) log.debug("isJson=" + isJson); try { StringBuilder destUrl = null; // Negotiate? if (isNegotiate) { // Send a GET request and pass the negotiate string as parameter String negoStr = new String(requestDataBuffer.array(), requestDataBuffer.position(), requestDataBuffer.limit(), "UTF-8"); negoStr = URLEncoder.encode(negoStr, "UTF-8"); String negoServlet = getServletPathForNegotiationAndAuthentication(); destUrl = getUrlStringBuilder(negoServlet); destUrl.append("&negotiate=").append(negoStr); // Clear session Cookie httpClient.clearHttpSession(); } // Reverse request (long-poll) ? else if ((msg.header.flags & BMessageHeader.FLAG_RESPONSE) != 0) { String longpollServlet = getServletPathForReverseRequest(); destUrl = getUrlStringBuilder(longpollServlet); timeoutSecondsRequest = 0; // timeout controlled by server, 10min by // default. } // Ordinary request else { destUrl = getUrlStringBuilder(""); } if (log.isDebugEnabled()) log.debug("open connection, url=" + destUrl); final HHttpRequest httpRequest = isNegotiate ? httpClient.get(destUrl.toString(), requestToCancel) : httpClient.post(destUrl.toString(), requestDataBuffer, requestToCancel); httpRequest.setTimeouts(timeoutSecondsClient, timeoutSecondsRequest); requestToCancel.setHttpRequest(httpRequest); addRequest(requestToCancel); } catch (Throwable e) { if (log.isDebugEnabled()) log.debug("received Throwable: " + e); BException bex = new BException(BExceptionC.IOERROR, "IO error", e); asyncResult.setAsyncResult(null, bex); } if (log.isDebugEnabled()) log.debug(")createRequestForMessage=" + requestToCancel); return requestToCancel; }