当前位置: 首页>>代码示例>>Java>>正文


Java ByteBuffer.clear方法代码示例

本文整理汇总了Java中java.nio.ByteBuffer.clear方法的典型用法代码示例。如果您正苦于以下问题:Java ByteBuffer.clear方法的具体用法?Java ByteBuffer.clear怎么用?Java ByteBuffer.clear使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.nio.ByteBuffer的用法示例。


在下文中一共展示了ByteBuffer.clear方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: mockServer

import java.nio.ByteBuffer; //导入方法依赖的package包/类
/**
 * MockServer plays the role of peer C. Respond to two requests for votes
 * with vote for self and then Assert.fail. 
 */
void mockServer() throws InterruptedException, IOException {          
    byte b[] = new byte[36];
    ByteBuffer responseBuffer = ByteBuffer.wrap(b);
    DatagramPacket packet = new DatagramPacket(b, b.length);
    QuorumServer server = peers.get(Long.valueOf(2));
    DatagramSocket udpSocket = new DatagramSocket(server.addr.getPort());
    LOG.info("In MockServer");
    mockLatch.countDown();
    Vote current = new Vote(2, 1);
    for (int i=0;i<2;++i) {
        udpSocket.receive(packet);
        responseBuffer.rewind();
        LOG.info("Received " + responseBuffer.getInt() + " " + responseBuffer.getLong() + " " + responseBuffer.getLong());
        LOG.info("From " + packet.getSocketAddress());
        responseBuffer.clear();
        responseBuffer.getInt(); // Skip the xid
        responseBuffer.putLong(2);
        
        responseBuffer.putLong(current.getId());
        responseBuffer.putLong(current.getZxid());
        packet.setData(b);
        udpSocket.send(packet);
    }
}
 
开发者ID:maoling,项目名称:fuck_zookeeper,代码行数:29,代码来源:LENonTerminateTest.java

示例2: getDirectByteBufferState

import java.nio.ByteBuffer; //导入方法依赖的package包/类
@Test
public void getDirectByteBufferState() {
    ByteBuffer dst = ByteBuffer.allocateDirect(4);
    dst.position(1);
    dst.limit(3);

    buffer.setByte(0, (byte) 1);
    buffer.setByte(1, (byte) 2);
    buffer.setByte(2, (byte) 3);
    buffer.setByte(3, (byte) 4);
    buffer.getBytes(1, dst);

    assertEquals(3, dst.position());
    assertEquals(3, dst.limit());

    dst.clear();
    assertEquals(0, dst.get(0));
    assertEquals(2, dst.get(1));
    assertEquals(3, dst.get(2));
    assertEquals(0, dst.get(3));
}
 
开发者ID:dachengxi,项目名称:EatDubbo,代码行数:22,代码来源:AbstractChannelBufferTest.java

示例3: sendHandshake

import java.nio.ByteBuffer; //导入方法依赖的package包/类
/**
	 * Sends handshake to remote peer.
	 * 
	 * @throws IOException
	 *             if an error occurs when writing to this connection's
	 *             {@link #java.nio.channels.SocketChannel}.
	 */
	public synchronized void sendHandshake() throws IOException {
//		System.out.println("WE have: " + PeerWireManager.allConnections.size() + " peers");
//		System.out.println("Are we blocking: " + clientSocketChannel.isBlocking());
//		System.out.println("Are we connected: " + clientSocketChannel.isConnected());
		ByteBuffer toSend = ByteBuffer.allocate(49 + PSTRLEN);
		toSend.clear();
		toSend.put(PSTRLEN);
		toSend.put(PSTR);
		toSend.putLong(0L);
		toSend.put(MetaInfo.INFO_HASH);
		toSend.put(MetaInfo.PEER_ID);
		toSend.flip();
		int huh = 0;
		while (toSend.hasRemaining()) {
			huh += clientSocketChannel.write(toSend);
		}
	//	System.out.println(huh);
		sentHandshake = true;
	}
 
开发者ID:jc0541,项目名称:URTorrent,代码行数:27,代码来源:PeerWireConnection.java

示例4: byCharsetEncoder_US_ASCII

import java.nio.ByteBuffer; //导入方法依赖的package包/类
@Benchmark
public byte[] byCharsetEncoder_US_ASCII() {
    try {
        CharsetEncoder encoder = asciiencode.get();
        CharBuffer buffer  = charbuffergenerator.get();
        buffer.clear();
        buffer.append(STR);
        buffer.flip();

        ByteBuffer outbuffer = bytebuffergenerator.get();
        outbuffer.clear();

        CoderResult result = encoder.encode(buffer, outbuffer, false);
        if (result.isError()) {
            result.throwException();
        }
        byte[] b = new byte[STR.length()];
        outbuffer.flip();
        outbuffer.get(b);
        return b;
    } catch (CharacterCodingException e) {
        throw new RuntimeException(e);
    }
}
 
开发者ID:fbacchella,项目名称:RegexPerf,代码行数:25,代码来源:StringToBytes.java

示例5: readFromFileChannel

import java.nio.ByteBuffer; //导入方法依赖的package包/类
protected int readFromFileChannel(Consumer<byte[]> buf, long offset, int size, FileChannel fileChannel) {
	if (fileChannel == null) {
		return -ErrorCodes.EBADF();
	}
	ByteBuffer byteBuffer = threadBuffer.get();
	byteBuffer.clear();
	byteBuffer.limit(size);
	return tryCatch.apply(() -> {
		int bytesRead = fileChannel.read(byteBuffer, offset); // Read into native memory
		if (bytesRead <= 0) { // EOF
			return SUCCESS;
		}
		byte[] intermediate = new byte[bytesRead]; // This copies native memory into JVM
		byteBuffer.rewind();
		byteBuffer.get(intermediate);
		buf.accept(intermediate); // And then back =(
		return bytesRead;
	});
}
 
开发者ID:tfiskgul,项目名称:mux2fs,代码行数:20,代码来源:MirrorFs.java

示例6: readHeader

import java.nio.ByteBuffer; //导入方法依赖的package包/类
/**
 * Populates the header with information received via socket
 */
public void readHeader() throws IOException {
  if (this.socket != null) {
    final ByteBuffer cb = getCommBuffer();
    synchronized (cb) {
      fetchHeader();
      final int type = cb.getInt();
      final int numParts = cb.getInt();
      final int txid = cb.getInt();
      cb.clear();
      if (!MessageType.validate(type)) {
        throw new IOException(
            LocalizedStrings.ChunkedMessage_INVALID_MESSAGE_TYPE_0_WHILE_READING_HEADER
                .toLocalizedString(Integer.valueOf(type)));
      }

      // Set the header and payload fields only after receiving all the
      // socket data, providing better message consistency in the face
      // of exceptional conditions (e.g. IO problems, timeouts etc.)
      this.msgType = type;
      this.numberOfParts = numParts; // Already set in setPayloadFields via setNumberOfParts
      this.transactionId = txid;
    }
  } else {
    throw new IOException(LocalizedStrings.ChunkedMessage_DEAD_CONNECTION.toLocalizedString());
  }
}
 
开发者ID:ampool,项目名称:monarch,代码行数:30,代码来源:ChunkedMessage.java

示例7: recycle

import java.nio.ByteBuffer; //导入方法依赖的package包/类
@Override
  public void recycle(ByteBuffer theBuf) {
  	
    	if(theBuf !=null && (!(theBuf instanceof DirectBuffer) )){
  		theBuf.clear();
  		return;
       }

    	final long size = theBuf.capacity();
boolean recycled = false;
DirectBuffer thisNavBuf = (DirectBuffer) theBuf;
int chunkCount = theBuf.capacity() / chunkSize;
DirectBuffer parentBuf = (DirectBuffer) thisNavBuf.attachment();
int startChunk = (int) ((thisNavBuf.address() - parentBuf.address()) / chunkSize);
for (int i = 0; i < allPages.length; i++) {
	if ((recycled = allPages[i].recycleBuffer((ByteBuffer) parentBuf, startChunk,chunkCount) == true)) {
		break;
	}
}

final long threadId = Thread.currentThread().getId();
if (memoryUsage.containsKey(threadId)) {
	memoryUsage.put(threadId, memoryUsage.get(threadId) - size);
}

if (recycled == false) {
	LOGGER.warn("warning , not recycled buffer " + theBuf);
}

sharedOptsCount++;	
  }
 
开发者ID:variflight,项目名称:feeyo-redisproxy,代码行数:32,代码来源:ByteBufferPagePool.java

示例8: eachItem

import java.nio.ByteBuffer; //导入方法依赖的package包/类
@Override
public void eachItem(final ImmutableDictionaryInfo info, final Consumer<DictionaryIndexItem> consumer) throws IOException {
	// The length of "word_str" should be less than 256.
	final ByteBuffer buf = ByteBuffer.allocate(256);

	int counter = 0;
	// index item format: word_str(256bytes) \0 word_data_offset(32/64bit)
	// word_data_size(32bit)
	while (null != info.getWordCount() && counter < info.getWordCount()) {
		byte b;
		try {
			b = this.in.readByte();
		} catch (EOFException ex) {
			break;
		}
		if (0 == b) {
			// get word_str
			buf.flip();
			final byte[] bytes = new byte[buf.limit()];
			buf.get(bytes);
			final String word = new String(bytes, Charset.forName("UTF-8"));
			buf.clear();

			// get offset
			final Long offset = Integer.valueOf(64).equals(info.getIdxOffsetBits()) ? this.in.readLong()
					: (long) this.in.readInt();

			// get size
			final Integer size = this.in.readInt();

			consumer.accept(new DictionaryIndexItem(word, offset, size));
			counter++;
		} else {
			buf.put(b);
		}
	}
}
 
开发者ID:sean-liang,项目名称:stardict,代码行数:38,代码来源:InputStreamDictionaryIndexReader.java

示例9: getTextureData

import java.nio.ByteBuffer; //导入方法依赖的package包/类
/**
* @see org.newdawn.slick.opengl.Texture#getTextureData()
*/
  public byte[] getTextureData() {
  	ByteBuffer buffer = BufferUtils.createByteBuffer((hasAlpha() ? 4 : 3) * texWidth * texHeight);
  	bind();
  	GL.glGetTexImage(SGL.GL_TEXTURE_2D, 0, hasAlpha() ? SGL.GL_RGBA : SGL.GL_RGB, SGL.GL_UNSIGNED_BYTE, 
  					   buffer);
  	byte[] data = new byte[buffer.limit()];
  	buffer.get(data);
  	buffer.clear();
  	
  	return data;
  }
 
开发者ID:IngSW-unipv,项目名称:Progetto-C,代码行数:15,代码来源:TextureImpl.java

示例10: decodeUrl

import java.nio.ByteBuffer; //导入方法依赖的package包/类
/**
 * Decodes the specified URL as per RFC 3986, i.e. transforms
 * percent-encoded octets to characters by decoding with the UTF-8 character
 * set. This function is primarily intended for usage with
 * {@link java.net.URL} which unfortunately does not enforce proper URLs. As
 * such, this method will leniently accept invalid characters or malformed
 * percent-encoded octets and simply pass them literally through to the
 * result string. Except for rare edge cases, this will make unencoded URLs
 * pass through unaltered.
 *
 * @param url The URL to decode, may be {@code null}.
 * @return The decoded URL or {@code null} if the input was
 * {@code null}.
 */
static String decodeUrl(String url) {
    String decoded = url;
    if (url != null && url.indexOf('%') >= 0) {
        int n = url.length();
        StringBuffer buffer = new StringBuffer();
        ByteBuffer bytes = ByteBuffer.allocate(n);
        for (int i = 0; i < n; ) {
            if (url.charAt(i) == '%') {
                try {
                    do {
                        byte octet = (byte) Integer.parseInt(url.substring(i + 1, i + 3), 16);
                        bytes.put(octet);
                        i += 3;
                    } while (i < n && url.charAt(i) == '%');
                    continue;
                } catch (RuntimeException e) {
                    // malformed percent-encoded octet, fall through and
                    // append characters literally
                } finally {
                    if (bytes.position() > 0) {
                        bytes.flip();
                        buffer.append(UTF8.decode(bytes).toString());
                        bytes.clear();
                    }
                }
            }
            buffer.append(url.charAt(i++));
        }
        decoded = buffer.toString();
    }
    return decoded;
}
 
开发者ID:jqjm,项目名称:Liteframework,代码行数:47,代码来源:FileUtils.java

示例11: read

import java.nio.ByteBuffer; //导入方法依赖的package包/类
/**
 * 
 * Read StarDict .syn file.
 * 
 * @param info
 *            dictionary meta data
 * @param in
 *            index file content in a ByteBuffer
 * 
 * @return synonyms index data
 */
public DictionarySynonymsIndex read(final ImmutableDictionaryInfo info, final ByteBuffer in) {
	// The length of "synonym_word" should be less than 256.
	final ByteBuffer buffer = ByteBuffer.allocate(256);

	int counter = 0;
	final DictionarySynonymsIndex index = new DictionarySynonymsIndex(info.getSynWordCount());
	// index item format: synonym_word(256bytes) \0
	// original_word_index(32/64bit)
	while (in.remaining() > 0 && (null != info.getSynWordCount() && counter < info.getSynWordCount())) {
		final byte b = in.get();
		if (0 == b) {
			// get synonym_word
			buffer.flip();
			final byte[] bytes = new byte[buffer.limit()];
			buffer.get(bytes);
			final String word = new String(bytes, Charset.forName("UTF-8"));
			buffer.clear();

			// get index
			final Integer offset = in.getInt();

			index.addItem(new DictionarySynonymsIndexItem(word, offset));
			counter++;
		} else {
			buffer.put(b);
		}
	}

	return index;
}
 
开发者ID:sean-liang,项目名称:stardict,代码行数:42,代码来源:DictionarySynonymsIndexReader.java

示例12: computeHash

import java.nio.ByteBuffer; //导入方法依赖的package包/类
public byte[] computeHash() throws IOException, NoSuchAlgorithmException {
	final int CHUNK_SIZE = 8192;
	try (FileLock lock = pieceChannel.lock()) {
		ByteBuffer buf = ByteBuffer.allocateDirect(CHUNK_SIZE);
		buf.clear();
		MessageDigest md = MessageDigest.getInstance("SHA-1");
		while (pieceChannel.read(buf) != -1) {
			buf.flip();
			md.update(buf);
			buf.clear();
		}
		return md.digest();
	}
	
}
 
开发者ID:jc0541,项目名称:URTorrent,代码行数:16,代码来源:PeerWirePiece.java

示例13: run

import java.nio.ByteBuffer; //导入方法依赖的package包/类
public void run() {
    SocketAddress sa = null;


    try {
        ByteBuffer bb = ByteBuffer.allocateDirect(12);
        bb.clear();
        // Get the one valid datagram
        dc.configureBlocking(false);
        while (sa == null) {
            sa = dc.receive(bb);
            if (sa != null && clientISA != null && !clientISA.equals(sa)) {
                log.println("Ignore a possible stray diagram from " + sa);
                sa = null;
            }
        }
        showBuffer("Received:", bb);
        sa = null;
        for (int i=0; i<100; i++) {
            bb.clear();
            sa = dc.receive(bb);
            if (sa != null)
                throw new RuntimeException("Test failed");
        }
        dc.close();
    } catch (Exception ex) {
        e = ex;
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:30,代码来源:Sender.java

示例14: discardToSps

import java.nio.ByteBuffer; //导入方法依赖的package包/类
/**
 * Discards data from the buffer up to the first SPS, where {@code data.position()} is interpreted
 * as the length of the buffer.
 * <p>
 * When the method returns, {@code data.position()} will contain the new length of the buffer. If
 * the buffer is not empty it is guaranteed to start with an SPS.
 *
 * @param data Buffer containing start code delimited NAL units.
 */
public static void discardToSps(ByteBuffer data) {
  int length = data.position();
  int consecutiveZeros = 0;
  int offset = 0;
  while (offset + 1 < length) {
    int value = data.get(offset) & 0xFF;
    if (consecutiveZeros == 3) {
      if (value == 1 && (data.get(offset + 1) & 0x1F) == NAL_UNIT_TYPE_SPS) {
        // Copy from this NAL unit onwards to the start of the buffer.
        ByteBuffer offsetData = data.duplicate();
        offsetData.position(offset - 3);
        offsetData.limit(length);
        data.position(0);
        data.put(offsetData);
        return;
      }
    } else if (value == 0) {
      consecutiveZeros++;
    }
    if (value != 0) {
      consecutiveZeros = 0;
    }
    offset++;
  }
  // Empty the buffer if the SPS NAL unit was not found.
  data.clear();
}
 
开发者ID:pooyafaroka,项目名称:PlusGram,代码行数:37,代码来源:NalUnitUtil.java

示例15: compressDecompressLoop

import java.nio.ByteBuffer; //导入方法依赖的package包/类
private void compressDecompressLoop(int rawDataSize) throws IOException {
  byte[] rawData = BytesGenerator.get(rawDataSize);    
  byte[] compressedResult = new byte[rawDataSize+20];
  int directBufferSize = Math.max(rawDataSize*2, 64*1024);    
  SnappyCompressor compressor = new SnappyCompressor(directBufferSize);
  compressor.setInput(rawData, 0, rawDataSize);
  int compressedSize = compressor.compress(compressedResult, 0, compressedResult.length);
  SnappyDirectDecompressor decompressor = new SnappyDirectDecompressor();
 
  ByteBuffer inBuf = ByteBuffer.allocateDirect(compressedSize);
  ByteBuffer outBuf = ByteBuffer.allocateDirect(rawDataSize);

  inBuf.put(compressedResult, 0, compressedSize);
  inBuf.flip();    

  ByteBuffer expected = ByteBuffer.wrap(rawData);
  
  outBuf.clear();
  while(!decompressor.finished()) {
    decompressor.decompress(inBuf, outBuf);
    if (outBuf.remaining() == 0) {
      outBuf.flip();
      while (outBuf.remaining() > 0) {        
        assertEquals(expected.get(), outBuf.get());
      }
      outBuf.clear();
    }
  }
  outBuf.flip();
  while (outBuf.remaining() > 0) {        
    assertEquals(expected.get(), outBuf.get());
  }
  outBuf.clear();
  
  assertEquals(0, expected.remaining());
}
 
开发者ID:naver,项目名称:hadoop,代码行数:37,代码来源:TestSnappyCompressorDecompressor.java


注:本文中的java.nio.ByteBuffer.clear方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。