List of usage examples for java.nio ByteBuffer put
public ByteBuffer put(ByteBuffer src)
From source file:nl.salp.warcraft4j.io.HttpDataReader.java
/** * {@inheritDoc}//from w ww . j a v a2s. co m */ @Override protected int readData(ByteBuffer buffer) throws DataReadingException { try { int read = 0; byte[] dataArray; if (buffer.hasArray()) { read = responseStream.read(buffer.array()); } else { byte[] data = new byte[buffer.capacity()]; read = responseStream.read(data); buffer.put(data); } return read; } catch (IOException e) { throw new DataReadingException(e); } }
From source file:au.org.ala.delta.io.BinFile.java
public void writeByte(byte b) { try {/*from w w w . java2 s. c o m*/ // _file.write(b); ByteBuffer bb = ByteBuffer.allocate(1); bb.order(ByteOrder.LITTLE_ENDIAN); bb.put(b); bb.position(0); _channel.write(bb); } catch (IOException ioex) { throw new RuntimeException(ioex); } }
From source file:au.org.ala.delta.io.BinFile.java
public void writeBytes(byte[] buffer) { try {//from w w w . java 2 s .c om ByteBuffer bb = ByteBuffer.allocate(buffer.length); bb.order(ByteOrder.LITTLE_ENDIAN); bb.put(buffer); bb.position(0); _channel.write(bb); // _file.write(buffer); } catch (IOException ioex) { throw new RuntimeException(ioex); } }
From source file:test.other.T_DaoTest.java
public void test2() throws SQLException, IOException { System.out.println(System.nanoTime() / 1000000); ResultSet rs = conn.createStatement().executeQuery("select content from fc_Post where id = 15"); rs.next();/*w w w . j ava 2 s.c o m*/ String text = rs.getString(1); System.out.println(text.length()); System.out.println(System.nanoTime() / 1000000); @SuppressWarnings("resource") FileChannel rwChannel = new RandomAccessFile("textfile.txt", "rw").getChannel(); ByteBuffer wrBuf = rwChannel.map(FileChannel.MapMode.READ_WRITE, 0, text.length() + 10); int lg = text.length() / 1000000; int pos = 0; byte[] buf = new byte[text.length() / 1000000]; System.out.println(System.nanoTime() / 1000000); for (int i = 0; i < 1000000; i++) { System.arraycopy(text.getBytes(), pos, buf, 0, lg); wrBuf.put(buf); pos += lg; } System.out.println(System.nanoTime() / 1000000); rwChannel.close(); }
From source file:com.tinspx.util.io.ChannelSourceTest.java
@Test public void testMemoizeSource() throws IOException { ByteSource source = of(ByteBuffer.allocate(16)); assertSame(source, ChannelSource.memoize(source)); source = of(new byte[16]); assertSame(source, ChannelSource.memoize(source)); source = memoize(ByteSource.empty()); assertSame(source, source);/* w ww . j a va2 s.c om*/ source = memoize(ByteSourceTests.force(of(INPUT))); assertTrue(source instanceof ChannelSource.MemoizeChannelSource); ByteSourceTests.testByteSource(source, INPUT); source = memoize(ByteSourceTests.force(of(ByteBuffer.wrap(INPUT)))); assertTrue(source instanceof ChannelSource.MemoizeChannelSource); ByteSourceTests.testByteSource(source, INPUT); source = memoize(ByteSourceTests.force(of(ByteBuffer.wrap(INPUT).asReadOnlyBuffer()))); assertTrue(source instanceof ChannelSource.MemoizeChannelSource); ByteSourceTests.testByteSource(source, INPUT); ByteBuffer direct = ByteBuffer.allocateDirect(INPUT.length); assertTrue(direct.isDirect()); direct.put(INPUT).flip(); source = memoize(ByteSourceTests.force(of(direct))); assertTrue(source instanceof ChannelSource.MemoizeChannelSource); ByteSourceTests.testByteSource(source, INPUT); source = memoize(new BAOutputStream(INPUT, INPUT.length).asByteSource()); assertTrue(source instanceof ChannelSource.MemoizeChannelSource); ByteSourceTests.testByteSource(source, INPUT); source = memoize(new ByteSourceTests.ForcedByteArray(INPUT)); assertTrue(source instanceof ChannelSource.MemoizeChannelSource); ByteSourceTests.testByteSource(source, INPUT); source = memoize(ByteSource.wrap(INPUT)); assertTrue(source instanceof ChannelSource.MemoizeChannelSource); ByteSourceTests.testByteSource(source, INPUT); ByteSourceTests.assertEmpty(memoize(ByteSource.empty())); ByteSourceTests.assertEmpty(memoize(ChannelSource.empty())); }
From source file:co.elastic.tealess.SSLChecker.java
private void checkHandshake(SSLReport sslReport, SocketChannel socket) { final InetSocketAddress address = sslReport.getAddress(); final String name = sslReport.getHostname(); IOObserver ioObserver = new IOObserver(); ObservingSSLEngine sslEngine = new ObservingSSLEngine(ctx.createSSLEngine(name, address.getPort()), ioObserver);// ww w. jav a2 s. c o m sslReport.setIOObserver(ioObserver); sslEngine.setUseClientMode(true); try { sslEngine.beginHandshake(); } catch (SSLException e) { sslReport.setFailed(e); Throwable cause = Blame.get(e); logger.warn("beginHandshake failed: [{}] {}", cause.getClass(), cause.getMessage()); } // TODO: Is this enough bytes? int size = sslEngine.getSession().getApplicationBufferSize() * 2; ByteBuffer localText = ByteBuffer.allocate(size); ByteBuffer localWire = ByteBuffer.allocate(size); ByteBuffer peerText = ByteBuffer.allocate(size); ByteBuffer peerWire = ByteBuffer.allocate(size); // TODO: I wonder... do we need to send any data at all? localText.put("SSL TEST. HELLO.".getBytes()); localText.flip(); SSLEngineResult result; logger.info("Starting SSL handshake [{}] ", address); try { SSLEngineResult.HandshakeStatus state; state = sslEngine.getHandshakeStatus(); while (state != FINISHED) { // XXX: Use a Selector to wait for data. //logger.trace("State: {} [{}]", state, address); switch (state) { case NEED_TASK: sslEngine.getDelegatedTask().run(); state = sslEngine.getHandshakeStatus(); break; case NEED_WRAP: localWire.clear(); result = sslEngine.wrap(localText, localWire); state = result.getHandshakeStatus(); localWire.flip(); while (localWire.hasRemaining()) { socket.write(localWire); //logger.trace("Sent {} bytes [{}]", bytes, address); } localWire.compact(); break; case NEED_UNWRAP: // Try reading until we get data. Selector selector = Selector.open(); while (peerWire.position() == 0) { socket.read(peerWire); try { Thread.currentThread().sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("Read " + peerWire.position() + " bytes"); peerWire.flip(); result = sslEngine.unwrap(peerWire, peerText); state = result.getHandshakeStatus(); peerWire.compact(); break; } } } catch (IOException e) { sslReport.setFailed(e); sslReport.setSSLSession(sslEngine.getHandshakeSession()); sslReport.setPeerCertificateDetails(peerCertificateDetails); logger.warn("beginHandshake failed", e); return; } logger.info("handshake completed [{}]", address); // Handshake OK! sslReport.setSSLSession(sslEngine.getSession()); }
From source file:com.yobidrive.diskmap.needles.Needle.java
public void putNeedleInBuffer(ByteBuffer result) throws Exception { int startPosition = result.position(); result.limit(result.capacity());/*from w w w. j av a2 s. co m*/ result.putInt(MAGICSTART); result.putLong(needleNumber); result.put(flags); result.putInt(keyBytes.length); result.put(keyBytes); result.putInt(version == null ? 0 : version.toBytes().length); if (version != null) result.put(version.toBytes()); result.putInt(previousNeedle == null ? -1 : previousNeedle.getNeedleFileNumber()); // Chaining result.putLong(previousNeedle == null ? -1L : previousNeedle.getNeedleOffset()); // Chaining result.putInt(originalFileNumber); // Original needle location (for cleaning) result.putInt(originalSize); // Original needle size (for cleaning) result.putInt(data == null ? 0 : data.length); if (data != null) result.put(data); result.putInt(MAGICEND); result.put(hashMD5()); while (((result.position() - startPosition) % 256) > 0) { result.put(PADDING); } result.flip(); }
From source file:jext2.DataInode.java
/** * Write data in buffer to disk. This works best when whole blocks which * are a multiple of blocksize in size are written. Partial blocks are * written by first reading the block and then writing the new data * to that buffer than write that new buffer to disk. * @throws NoSpaceLeftOnDevice/*from ww w . ja v a 2 s.co m*/ * @throws FileTooLarge */ public int writeData(ByteBuffer buf, long offset) throws JExt2Exception, NoSpaceLeftOnDevice, FileTooLarge { /* * Note on sparse file support: * getBlocksAllocate does not care if there are holes. Just write as much * blocks as the buffer requires at the desired location an set inode.size * accordingly. */ int blocksize = superblock.getBlocksize(); long start = offset / blocksize; long end = (buf.capacity() + blocksize) / blocksize + start; int startOff = (int) (offset % blocksize); if (startOff > 0) end += 1; buf.rewind(); while (start < end) { LinkedList<Long> blockNrs = accessData().getBlocksAllocate(start, 1); int bytesLeft = buf.capacity() - buf.position(); if (bytesLeft < blocksize || startOff > 0) { /* write partial block */ ByteBuffer onDisk = blockAccess.read(blockNrs.getFirst()); onDisk.position(startOff); assert onDisk.limit() == blocksize; buf.limit(buf.position() + Math.min(bytesLeft, onDisk.remaining())); onDisk.put(buf); onDisk.position(startOff); blockAccess.writeFromBufferUnsynchronized((blockNrs.getFirst() & 0xffffffff) * blocksize, onDisk); } else { /* write whole block */ buf.limit(buf.position() + blocksize); blockAccess.writeFromBufferUnsynchronized((blockNrs.getFirst() & 0xffffffff) * blocksize, buf); } start += 1; startOff = 0; accessData().unlockHierarchyChanges(); } int written = buf.position(); assert written == buf.capacity(); /* increase inode.size if we grew the file */ if (offset + written > getSize()) { /* file grew */ setStatusChangeTime(new Date()); setSize(offset + written); } return written; }
From source file:net.dv8tion.jda.core.audio.AudioWebSocket.java
private void setupKeepAlive(final int keepAliveInterval) { if (keepAliveHandle != null) LOG.fatal("Setting up a KeepAlive runnable while the previous one seems to still be active!!"); Runnable keepAliveRunnable = () -> { if (socket.isOpen() && socket.isOpen() && !udpSocket.isClosed()) { send(new JSONObject().put("op", 3).put("d", System.currentTimeMillis()).toString()); long seq = 0; try { ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES + 1); buffer.put((byte) 0xC9); buffer.putLong(seq);/*from w w w . j av a2 s. co m*/ DatagramPacket keepAlivePacket = new DatagramPacket(buffer.array(), buffer.array().length, address); udpSocket.send(keepAlivePacket); } catch (NoRouteToHostException e) { LOG.warn("Closing AudioConnection due to inability to ping audio packets."); LOG.warn("Cannot send audio packet because JDA navigate the route to Discord.\n" + "Are you sure you have internet connection? It is likely that you've lost connection."); AudioWebSocket.this.close(ConnectionStatus.ERROR_LOST_CONNECTION); } catch (IOException e) { LOG.log(e); } } }; try { keepAliveHandle = keepAlivePool.scheduleAtFixedRate(keepAliveRunnable, 0, keepAliveInterval, TimeUnit.MILLISECONDS); } catch (RejectedExecutionException ignored) { } //ignored because this is probably caused due to a race condition // related to the threadpool shutdown. }
From source file:au.org.ala.delta.io.BinFile.java
public void setLength(int newLength) { try {/*from w w w .j av a 2s .c o m*/ // _file.setLength(newLength); int currentPos = tell(); _channel.position(_channel.size()); long growSize = newLength - _channel.size(); ByteBuffer dummyBuffer = ByteBuffer.allocate((int) growSize); for (int i = 0; i < growSize; i++) { dummyBuffer.put((byte) 0); } dummyBuffer.position(0); _channel.write(dummyBuffer); seek(currentPos); } catch (IOException e) { throw new RuntimeException(e); } }