List of usage examples for java.nio ByteBuffer array
public final byte[] array()
From source file:net.sf.jml.message.p2p.MsnP2PMessage.java
/** * @see MsnMimeMessage#toOutgoingMsg(MsnProtocol) *//* w w w .j a v a 2s .co m*/ @Override public OutgoingMSG[] toOutgoingMsg(MsnProtocol protocol) { OutgoingMSG message = new OutgoingMSG(protocol); message.setMsgType(OutgoingMSG.TYPE_MSNC1); byte[] mimeMessageHeader = Charset.encodeAsByteArray(toString()); byte[] body = bodyToMessage(); if (body == null) { body = new byte[0]; } ByteBuffer msg = ByteBuffer .allocate(mimeMessageHeader.length + BINARY_HEADER_LEN + body.length + BINARY_FOOTER_LEN); msg.put(mimeMessageHeader); msg.put(binaryHeader); msg.put(body); msg.put(binaryFooter); message.setMsg(msg.array()); return new OutgoingMSG[] { message }; }
From source file:com.github.ambry.utils.UtilsTest.java
@Test public void testReadFileToByteBuffer() throws IOException { File file = File.createTempFile("test", "1"); file.deleteOnExit();/*from w w w .jav a2 s . c o m*/ FileChannel fileChannel = Utils.openChannel(file, false); byte[] referenceBytes = new byte[20]; new Random().nextBytes(referenceBytes); FileUtils.writeByteArrayToFile(file, referenceBytes); // fill up fresh byteBuffer ByteBuffer buffer = ByteBuffer.allocate(20); Utils.readFileToByteBuffer(fileChannel, 0, buffer); assertArrayEquals("Data mismatch", referenceBytes, buffer.array()); // write to byteBuffer based on buffer remaining buffer.limit(10); buffer.position(0); assertEquals("buffer remaining should be 10", 10, buffer.remaining()); Utils.readFileToByteBuffer(fileChannel, 10, buffer); assertEquals("buffer remaining should be 0", 0, buffer.remaining()); for (int i = 0; i < 10; i++) { assertEquals("First 10 bytes in buffer should match last 10 bytes in file", buffer.array()[i], referenceBytes[i + 10]); } // byteBuffer.remaining() + starting offset > file size, exception is expected. buffer.clear(); assertEquals("buffer remaining should be 20", 20, buffer.remaining()); try { Utils.readFileToByteBuffer(fileChannel, 1, buffer); fail("Should fail"); } catch (IOException e) { } // starting offset exceeds file size, exception is expected. buffer.clear(); assertEquals("buffer remaining should be 20", 20, buffer.remaining()); try { Utils.readFileToByteBuffer(fileChannel, 21, buffer); fail("Should fail"); } catch (IOException e) { } }
From source file:com.owncloud.android.oc_framework.network.webdav.FileRequestEntity.java
@Override public void writeRequest(final OutputStream out) throws IOException { //byte[] tmp = new byte[4096]; ByteBuffer tmp = ByteBuffer.allocate(4096); int readResult = 0; // TODO(bprzybylski): each mem allocation can throw OutOfMemoryError we need to handle it // globally in some fashionable manner RandomAccessFile raf = new RandomAccessFile(mFile, "r"); FileChannel channel = raf.getChannel(); Iterator<OnDatatransferProgressListener> it = null; long transferred = 0; long size = mFile.length(); if (size == 0) size = -1;/*from www . ja v a2 s.c om*/ try { while ((readResult = channel.read(tmp)) >= 0) { out.write(tmp.array(), 0, readResult); tmp.clear(); transferred += readResult; synchronized (mDataTransferListeners) { it = mDataTransferListeners.iterator(); while (it.hasNext()) { it.next().onTransferProgress(readResult, transferred, size, mFile.getName()); } } } } catch (IOException io) { Log.e("FileRequestException", io.getMessage()); throw new RuntimeException( "Ugly solution to workaround the default policy of retries when the server falls while uploading ; temporal fix; really", io); } finally { channel.close(); raf.close(); } }
From source file:eu.alefzero.webdav.FileRequestEntity.java
@Override public void writeRequest(final OutputStream out) throws IOException { //byte[] tmp = new byte[4096]; ByteBuffer tmp = ByteBuffer.allocate(4096); int readResult = 0; // TODO(bprzybylski): each mem allocation can throw OutOfMemoryError we need to handle it // globally in some fashionable manner RandomAccessFile raf = new RandomAccessFile(mFile, "r"); FileChannel channel = raf.getChannel(); Iterator<OnDatatransferProgressListener> it = null; long transferred = 0; long size = mFile.length(); if (size == 0) size = -1;/*from w w w.j a va2 s . c o m*/ try { while ((readResult = channel.read(tmp)) >= 0) { out.write(tmp.array(), 0, readResult); tmp.clear(); transferred += readResult; synchronized (mDataTransferListeners) { it = mDataTransferListeners.iterator(); while (it.hasNext()) { it.next().onTransferProgress(readResult, transferred, size, mFile.getName()); } } } } catch (IOException io) { Log_OC.e("FileRequestException", io.getMessage()); throw new RuntimeException( "Ugly solution to workaround the default policy of retries when the server falls while uploading ; temporal fix; really", io); } finally { channel.close(); raf.close(); } }
From source file:edu.cmu.cylab.starslinger.transaction.WebEngine.java
/** * get a file, based on the retrieval id from the server * // w w w . j av a 2s . co m * @throws MessageNotFoundException */ public byte[] getFile(byte[] msgHashBytes) throws ExchangeException, MessageNotFoundException { ByteBuffer msg = ByteBuffer.allocate(mVersionLen // + 4 + msgHashBytes.length // ); msg.putInt(mVersion); msg.putInt(msgHashBytes.length); msg.put(msgHashBytes); byte[] resp = doPost(mUrlPrefix + mHost + "/getFile" + mUrlSuffix, msg.array()); resp = handleResponseExceptions(resp, 0); return resp; }
From source file:edu.cmu.cylab.starslinger.transaction.WebEngine.java
/** * get a message meta-data, based on the retrieval id from the server * /*from ww w . j a v a2s.c om*/ * @throws MessageNotFoundException */ public byte[] getMessage(byte[] msgHashBytes) throws ExchangeException, MessageNotFoundException { ByteBuffer msg = ByteBuffer.allocate(mVersionLen // + 4 + msgHashBytes.length // ); msg.putInt(mVersion); msg.putInt(msgHashBytes.length); msg.put(msgHashBytes); byte[] resp = doPost(mUrlPrefix + mHost + "/getMessage" + mUrlSuffix, msg.array()); resp = handleResponseExceptions(resp, 0); return resp; }
From source file:com.cerema.cloud2.lib.common.network.FileRequestEntity.java
@Override public void writeRequest(final OutputStream out) throws IOException { //byte[] tmp = new byte[4096]; ByteBuffer tmp = ByteBuffer.allocate(4096); int readResult = 0; // TODO(bprzybylski): each mem allocation can throw OutOfMemoryError we need to handle it // globally in some fashionable manner RandomAccessFile raf = new RandomAccessFile(mFile, "r"); FileChannel channel = raf.getChannel(); Iterator<OnDatatransferProgressListener> it = null; long transferred = 0; long size = mFile.length(); if (size == 0) size = -1;//from ww w. j av a 2 s . co m try { while ((readResult = channel.read(tmp)) >= 0) { out.write(tmp.array(), 0, readResult); tmp.clear(); transferred += readResult; synchronized (mDataTransferListeners) { it = mDataTransferListeners.iterator(); while (it.hasNext()) { it.next().onTransferProgress(readResult, transferred, size, mFile.getAbsolutePath()); } } } } catch (IOException io) { Log_OC.e("FileRequestException", io.getMessage()); throw new RuntimeException( "Ugly solution to workaround the default policy of retries when the server falls while uploading ; temporal fix; really", io); } finally { channel.close(); raf.close(); } }
From source file:com.github.ambry.utils.UtilsTest.java
@Test public void testReadBuffers() throws IOException { byte[] buf = new byte[40004]; new Random().nextBytes(buf); ByteBuffer inputBuf = ByteBuffer.wrap(buf); inputBuf.putInt(0, 40000);/*from w w w. jav a 2 s. c om*/ ByteBuffer outputBuf = Utils.readIntBuffer(new DataInputStream(new ByteBufferInputStream(inputBuf))); for (int i = 0; i < 40000; i++) { Assert.assertEquals(buf[i + 4], outputBuf.array()[i]); } // 0 size inputBuf.rewind(); inputBuf.putInt(0, 0); outputBuf = Utils.readIntBuffer(new DataInputStream(new ByteBufferInputStream(inputBuf))); Assert.assertEquals("Output should be of length 0", 0, outputBuf.array().length); // negative size inputBuf.rewind(); inputBuf.putInt(0, -1); try { Utils.readIntBuffer(new DataInputStream(new ByteBufferInputStream(inputBuf))); Assert.fail("Should have encountered exception with negative length."); } catch (IllegalArgumentException e) { } buf = new byte[10]; new Random().nextBytes(buf); inputBuf = ByteBuffer.wrap(buf); inputBuf.putShort(0, (short) 8); outputBuf = Utils.readShortBuffer(new DataInputStream(new ByteBufferInputStream(inputBuf))); for (int i = 0; i < 8; i++) { Assert.assertEquals(buf[i + 2], outputBuf.array()[i]); } // 0 size inputBuf.rewind(); inputBuf.putShort(0, (short) 0); outputBuf = Utils.readShortBuffer(new DataInputStream(new ByteBufferInputStream(inputBuf))); Assert.assertEquals("Output should be of length 0", 0, outputBuf.array().length); // negative size inputBuf.rewind(); inputBuf.putShort(0, (short) -1); try { Utils.readShortBuffer(new DataInputStream(new ByteBufferInputStream(inputBuf))); Assert.fail("Should have encountered exception with negative length."); } catch (IllegalArgumentException e) { } }
From source file:org.jhk.pulsing.web.aspect.UserDaoAspect.java
@AfterReturning(pointcut = "execution(org.jhk.pulsing.web.common.Result+ org.jhk.pulsing.web.dao.*.UserDao.*(..))", returning = "result") public void patchUser(JoinPoint joinPoint, Result<User> result) { if (result.getCode() != SUCCESS) { return;//from w w w. java 2 s .c o m } User user = result.getData(); user.setPassword(""); //blank out password Picture picture = user.getPicture(); _LOGGER.debug("UserDaoAspect.setPictureUrl" + user); if (picture != null && picture.getName() != null) { ByteBuffer pBuffer = picture.getContent(); String path = applicationContext.getServletContext().getRealPath("/resources/img"); File parent = Paths.get(path).toFile(); if (!parent.exists()) { parent.mkdirs(); } String pFileName = user.getId().getId() + "_" + pBuffer.hashCode() + "_" + picture.getName(); File pFile = Paths.get(path, pFileName).toFile(); if (!pFile.exists()) { try (OutputStream fStream = Files.newOutputStream(pFile.toPath(), StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE)) { fStream.write(pBuffer.array()); } catch (IOException iException) { iException.printStackTrace(); pFile = null; } } if (pFile != null) { _LOGGER.debug("UserDaoAspect Setting picture url - " + _RESOURCE_PREFIX + pFile.getName()); picture.setUrl(_RESOURCE_PREFIX + pFile.getName()); } } }