List of usage examples for java.nio ByteBuffer clear
public final Buffer clear()
From source file:com.github.neoio.net.message.staging.file.TestFileMessageStaging.java
@Test public void test() throws Exception { ByteBuffer buffer = ByteBuffer.allocate(1024); buffer.put("Hello World".getBytes("US-ASCII")); buffer.flip();/*from w ww .java 2 s .c o m*/ Assert.assertEquals(11, staging.writeTempReadBytes(buffer)); Assert.assertTrue(staging.hasTempReadBytes()); buffer.clear(); Assert.assertEquals(11, staging.readTempReadBytes(buffer)); buffer.put("Hello World".getBytes("US-ASCII")); buffer.flip(); staging.writePrimaryStaging(buffer, 22); buffer.clear(); staging.getPrimaryStage().read(buffer); Assert.assertEquals("Hello WorldHello World", new String(buffer.array(), 0, 22)); }
From source file:org.apache.hadoop.tracing.TestTracing.java
private void readTestFile(String testFileName) throws Exception { Path filePath = new Path(testFileName); FSDataInputStream istream = dfs.open(filePath, 10240); ByteBuffer buf = ByteBuffer.allocate(10240); int count = 0; try {/*from ww w . j a v a 2 s . c o m*/ while (istream.read(buf) > 0) { count += 1; buf.clear(); istream.seek(istream.getPos() + 5); } } catch (IOException ioe) { // Ignore this it's probably a seek after eof. } finally { istream.close(); } }
From source file:com.sastix.cms.server.services.cache.CacheFileUtilsServiceImpl.java
@Override public byte[] downloadResource(URL url) throws IOException { //create buffer with capacity in bytes ByteArrayOutputStream baos = new ByteArrayOutputStream(); try {//ww w .ja v a 2 s . co m ByteBuffer bufIn = ByteBuffer.allocate(1024); ReadableByteChannel rbc = Channels.newChannel(url.openStream()); int bytesRead; while ((bytesRead = rbc.read(bufIn)) > 0) { baos.write(bufIn.array(), 0, bytesRead); bufIn.rewind(); } bufIn.clear(); return baos.toByteArray(); } finally { baos.close(); } }
From source file:org.talend.studio.StudioInstaller.java
boolean checkFile(File file, String data) { FileInputStream fis = null;/*ww w . ja v a 2s.c om*/ try { MessageDigest md5 = MessageDigest.getInstance("MD5"); fis = new FileInputStream(file); FileChannel fc = fis.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024); while (true) { int length = fc.read(buffer); if (length < 1) { break; } buffer.flip(); md5.update(buffer); buffer.clear(); } byte[] ret = md5.digest(); return BuildUtil.toHexString(ret).equals(data.trim().toUpperCase()); } catch (Exception e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(fis); } return false; }
From source file:org.apache.hadoop.hbase.client.TestResult.java
public void testBasicLoadValue() throws Exception { KeyValue[] kvs = genKVs(row, family, value, 1, 100); Arrays.sort(kvs, KeyValue.COMPARATOR); Result r = Result.create(kvs); ByteBuffer loadValueBuffer = ByteBuffer.allocate(1024); for (int i = 0; i < 100; ++i) { final byte[] qf = Bytes.toBytes(i); loadValueBuffer.clear(); r.loadValue(family, qf, loadValueBuffer); loadValueBuffer.flip();/*from w w w . ja v a 2 s . co m*/ assertEquals(ByteBuffer.wrap(Bytes.add(value, Bytes.toBytes(i))), loadValueBuffer); assertEquals(ByteBuffer.wrap(Bytes.add(value, Bytes.toBytes(i))), r.getValueAsByteBuffer(family, qf)); } }
From source file:org.cloudata.core.commitlog.pipe.Bulk.java
private void addNewBuffersToList() { for (ByteBuffer buf : BufferPool.singleton().getBuffer(DEFAULT_BUFFER_SIZE)) { LOG.debug("add new buffer"); buf.clear(); bufferList.add(buf);/*from ww w . ja v a2 s.c o m*/ } }
From source file:siddur.solidtrust.classic.ClassicController.java
@RequestMapping(value = "/upload", method = RequestMethod.POST) public String handleFormUpload(@RequestParam("file") MultipartFile file, Model model, HttpSession session) throws Exception { //upload/* w ww.j av a2s . co m*/ log4j.info("Start uploading file: " + file.getName() + " with size: " + file.getSize()); File temp = File.createTempFile("data", ".csv"); log4j.info("Will save to " + temp.getAbsolutePath()); InputStream in = null; FileOutputStream fout = null; try { fout = new FileOutputStream(temp); FileChannel fcout = fout.getChannel(); in = file.getInputStream(); ReadableByteChannel cin = Channels.newChannel(in); ByteBuffer buf = ByteBuffer.allocate(1024 * 8); while (true) { buf.clear(); int r = cin.read(buf); if (r == -1) { break; } buf.flip(); fcout.write(buf); } } finally { if (in != null) { in.close(); } if (fout != null) { fout.close(); } } log4j.info("Uploading complete"); //fields BufferedReader br = null; int[] orders; try { in = new FileInputStream(temp); br = new BufferedReader(new InputStreamReader(in)); //first line for fields String firstLine = br.readLine(); orders = persister.validateTitle(firstLine); //persist persister.parseAndSave(br, orders, persister); } finally { if (br != null) { br.close(); } } return "redirect:upload.html"; }
From source file:com.sm.connector.server.ServerStore.java
protected Pair<byte[], byte[]> next(int current, ByteBuffer buf) throws IOException { buf.clear(); long pos = OFFSET + (long) current * RECORD_SIZE; indexChannel.read(buf, pos);/*from w w w . jav a 2 s . c o m*/ buf.rewind(); byte status = buf.get(); if (isDeleted(status)) { return null; } else { long keyLen = buf.getLong(); byte[] keys = readChannel(keyLen, keyChannel); long data = buf.getLong(); long block2version = buf.getLong(); CacheBlock block = new CacheBlock(current, data, block2version, status); if (block.getDataOffset() <= 0 || block.getDataLen() <= 0 || block.getBlockSize() < block.getDataLen()) { throw new StoreException("data reading error"); } else { //Key key = toKey(keys); byte[] datas = readChannel(block.getDataOffset2Len(), dataChannel); return new Pair(keys, datas); } } }
From source file:com.offbynull.portmapper.natpmp.NatPmpReceiver.java
/** * Start listening for NAT-PMP events. This method blocks until {@link #stop() } is called. * @param listener listener to notify of events * @throws IOException if socket error occurs * @throws NullPointerException if any argument is {@code null} *//*from w w w . j a v a2s. com*/ public void start(NatPmpEventListener listener) throws IOException { Validate.notNull(listener); MulticastSocket socket = null; try { final InetAddress group = InetAddress.getByName("224.0.0.1"); // NOPMD final int port = 5350; final InetSocketAddress groupAddress = new InetSocketAddress(group, port); socket = new MulticastSocket(port); if (!currentSocket.compareAndSet(null, socket)) { IOUtils.closeQuietly(socket); return; } socket.setReuseAddress(true); Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface networkInterface = interfaces.nextElement(); Enumeration<InetAddress> addrs = networkInterface.getInetAddresses(); while (addrs.hasMoreElements()) { // make sure atleast 1 ipv4 addr bound to interface InetAddress addr = addrs.nextElement(); try { if (addr instanceof Inet4Address) { socket.joinGroup(groupAddress, networkInterface); } } catch (IOException ioe) { // NOPMD // occurs with certain interfaces // do nothing } } } ByteBuffer buffer = ByteBuffer.allocate(12); DatagramPacket data = new DatagramPacket(buffer.array(), buffer.capacity()); while (true) { buffer.clear(); socket.receive(data); buffer.position(data.getLength()); buffer.flip(); if (!data.getAddress().equals(gatewayAddress)) { // data isn't from our gateway, ignore continue; } if (buffer.remaining() != 12) { // data isn't the expected size, ignore continue; } int version = buffer.get(0); if (version != 0) { // data doesn't have the correct version, ignore continue; } int opcode = buffer.get(1) & 0xFF; if (opcode != 128) { // data doesn't have the correct op, ignore continue; } int resultCode = buffer.getShort(2) & 0xFFFF; switch (resultCode) { case 0: break; default: continue; // data doesn't have a successful result, ignore } listener.publicAddressUpdated(new ExternalAddressNatPmpResponse(buffer)); } } catch (IOException ioe) { if (currentSocket.get() == null) { return; // ioexception caused by interruption/stop, so just return without propogating error up } throw ioe; } finally { IOUtils.closeQuietly(socket); currentSocket.set(null); } }
From source file:org.apache.kylin.storage.hbase.cube.v1.filter.TestFuzzyRowFilterV2EndToEnd.java
@SuppressWarnings("unchecked") private void runTest(HTable hTable, int expectedSize) throws IOException { // [0, 2, ?, ?, ?, ?, 0, 0, 0, 1] byte[] fuzzyKey1 = new byte[10]; ByteBuffer buf = ByteBuffer.wrap(fuzzyKey1); buf.clear(); buf.putShort((short) 2); for (int i = 0; i < 4; i++) buf.put(fuzzyValue);/*from w w w . j ava2s . c o m*/ buf.putInt((short) 1); byte[] mask1 = new byte[] { 0, 0, 1, 1, 1, 1, 0, 0, 0, 0 }; byte[] fuzzyKey2 = new byte[10]; buf = ByteBuffer.wrap(fuzzyKey2); buf.clear(); buf.putShort((short) 2); buf.putInt((short) 2); for (int i = 0; i < 4; i++) buf.put(fuzzyValue); byte[] mask2 = new byte[] { 0, 0, 0, 0, 0, 0, 1, 1, 1, 1 }; Pair<byte[], byte[]> pair1 = Pair.newPair(fuzzyKey1, mask1); Pair<byte[], byte[]> pair2 = Pair.newPair(fuzzyKey2, mask2); FuzzyRowFilterV2 fuzzyRowFilter1 = new FuzzyRowFilterV2(Lists.newArrayList(pair1)); FuzzyRowFilterV2 fuzzyRowFilter2 = new FuzzyRowFilterV2(Lists.newArrayList(pair2)); // regular test - we expect 1 row back (5 KVs) runScanner(hTable, expectedSize, fuzzyRowFilter1, fuzzyRowFilter2); }