List of usage examples for java.nio ByteBuffer allocate
public static ByteBuffer allocate(int capacity)
From source file:net.fenyo.extension.Dns.TcpSocket.java
@Override public void run() { if (read_thread) { read_thread = false;/*from w w w . j a v a2 s . c o m*/ new Thread(this).start(); try { // thread de lecture locale pour envoi au serveur while (true) { final ByteBuffer tmp_read_buf = ByteBuffer.allocate(1024); int ret = socket_channel.read(tmp_read_buf); if (ret >= 0) { tmp_read_buf.flip(); synchronized (read_buf) { read_buf.put(tmp_read_buf); } } else { synchronized (closed) { if (!closed) socket_channel.close(); closed = true; } return; } } } catch (IOException e) { Log.e("TcpSocket:run(): read(): ", "IOException"); e.printStackTrace(); try { synchronized (closed) { if (!closed) socket_channel.close(); closed = true; } } catch (IOException e1) { Log.e("TcpSocket:run(): close(): ", "IOException"); e1.printStackTrace(); } return; } finally { tcp_init.removeSocket(id); terminateLocalWriteThread(); // Log.i("Alex", "femeture thread 1 id=" + id); } } else { try { // thread de lecture distante pour crire sur socket locale while (true) { synchronized (write_buf_sem) { if (must_exit == true) return; try { if (write_buf.length == 0) { if (must_exit_when_all_data_read_locally) { try { socket_channel.close(); } catch (IOException e) { Log.e("TcpSocket:closeSocket()", "Exception"); e.printStackTrace(); } return; } write_buf_sem.wait(); } } catch (InterruptedException e) { // e.printStackTrace(); return; } } ByteBuffer _write_buf; synchronized (write_buf_sem) { _write_buf = ByteBuffer.allocate(write_buf.length); _write_buf.put(write_buf); } _write_buf.flip(); int nbytes = socket_channel.write(_write_buf); synchronized (write_buf_sem) { final byte[] new_write_buf = new byte[write_buf.length - nbytes]; for (int i = 0; i < write_buf.length - nbytes; i++) new_write_buf[i] = write_buf[i + nbytes]; write_buf = new_write_buf; } } } catch (IOException e) { Log.e("TcpSocket:run(): write(): ", "IOException"); e.printStackTrace(); try { synchronized (closed) { if (!closed) socket_channel.close(); closed = true; } } catch (IOException e1) { Log.e("TcpSocket:run(): close(): ", "IOException"); e1.printStackTrace(); } return; } finally { // Log.i("Alex", "femeture thread 2 id=" + id); } } }
From source file:com.sm.connector.server.ServerStore.java
/** * * @param begin of record no, it is zero based * @param size// ww w .j a va 2s. co m * @return */ public List<Pair<byte[], byte[]>> nextBlock(int begin, int size) { if (begin > totalRecord - 1) return new ArrayList<Pair<byte[], byte[]>>(); else { List<Pair<byte[], byte[]>> list = new ArrayList<Pair<byte[], byte[]>>(size); ByteBuffer buf = ByteBuffer.allocate(RECORD_SIZE); int current = begin; while (hasNext()) { try { Pair<byte[], byte[]> pair = next(current, buf); if (pair != null) { list.add(pair); current++; if (current >= begin + size) break; } } catch (Exception ex) { logger.error(ex.getMessage(), ex); } } logger.info("nextBlock begin " + begin + " size " + list.size()); return list; } }
From source file:com.github.ambry.utils.UtilsTest.java
@Test public void testReadStrings() throws IOException { // good case/* w ww . j a v a 2 s.c o m*/ ByteBuffer buffer = ByteBuffer.allocate(10); buffer.putShort((short) 8); String s = getRandomString(8); buffer.put(s.getBytes()); buffer.flip(); String outputString = Utils.readShortString(new DataInputStream(new ByteBufferInputStream(buffer))); Assert.assertEquals(s, outputString); // 0-length buffer.rewind(); buffer.putShort(0, (short) 0); outputString = Utils.readShortString(new DataInputStream(new ByteBufferInputStream(buffer))); Assert.assertTrue(outputString.isEmpty()); // failed case buffer.rewind(); buffer.putShort((short) 10); buffer.put(s.getBytes()); buffer.flip(); try { outputString = Utils.readShortString(new DataInputStream(new ByteBufferInputStream(buffer))); Assert.assertTrue(false); } catch (IllegalArgumentException e) { Assert.assertTrue(true); } buffer.rewind(); buffer.putShort(0, (short) -1); try { outputString = Utils.readShortString(new DataInputStream(new ByteBufferInputStream(buffer))); Assert.fail("Should have encountered exception with negative length."); } catch (IllegalArgumentException e) { } // good case buffer = ByteBuffer.allocate(40004); buffer.putInt(40000); s = getRandomString(40000); buffer.put(s.getBytes()); buffer.flip(); outputString = Utils.readIntString(new DataInputStream(new ByteBufferInputStream(buffer)), StandardCharsets.UTF_8); Assert.assertEquals(s, outputString); // 0-length buffer.rewind(); buffer.putInt(0, 0); outputString = Utils.readShortString(new DataInputStream(new ByteBufferInputStream(buffer))); Assert.assertTrue(outputString.isEmpty()); // failed case buffer.rewind(); buffer.putInt(50000); buffer.put(s.getBytes()); buffer.flip(); try { outputString = Utils.readIntString(new DataInputStream(new ByteBufferInputStream(buffer)), StandardCharsets.UTF_8); fail("Should have failed"); } catch (IllegalArgumentException e) { // expected. } buffer.rewind(); buffer.putInt(0, -1); try { Utils.readIntString(new DataInputStream(new ByteBufferInputStream(buffer)), StandardCharsets.UTF_8); Assert.fail("Should have encountered exception with negative length."); } catch (IllegalArgumentException e) { // expected. } }
From source file:ch.ledcom.jpreseed.UsbCreatorTest.java
private CpioArchiveInputStream getCpioArchiveInputStream(FsDirectoryEntry newInitRdGzEntry) throws IOException { FsFile initrdGzFile = newInitRdGzEntry.getFile(); ByteBuffer initRdBuffer = ByteBuffer.allocate((int) initrdGzFile.getLength()); initrdGzFile.read(0, initRdBuffer);// www. j a va 2 s. c om initRdBuffer.rewind(); return new CpioArchiveInputStream(new GZIPInputStream(new ByteBufferDataInputStream(initRdBuffer))); }
From source file:com.alibaba.otter.shared.common.utils.NioUtilsPerformance.java
public static void channelTest(File source, File target) throws Exception { FileInputStream fis = null;//www . j a v a 2s.com FileOutputStream fos = null; try { fis = new FileInputStream(source); fos = new FileOutputStream(target); FileChannel sChannel = fis.getChannel(); FileChannel tChannel = fos.getChannel(); target.createNewFile(); ByteBuffer buffer = ByteBuffer.allocate(16 * 1024); while (sChannel.read(buffer) > 0) { buffer.flip(); tChannel.write(buffer); buffer.clear(); } tChannel.close(); sChannel.close(); } finally { IOUtils.closeQuietly(fis); IOUtils.closeQuietly(fos); } }
From source file:net.anidb.udp.UdpResponse.java
/** * Returns a instance of the class./*from ww w .j a v a 2s . co m*/ * @param packet The datagram packet. * @param charset The charset. * @return The instance. * @throws IllegalArgumentException If the datagram packet is * <code>null</code>. * @throws UdpConnectionException If the structure of datagram packet isn't * valid. * @throws UnsupportedEncodingException If the given charset isn't * supported. */ protected static UdpResponse getInstance(final DatagramPacket packet, final Charset charset) throws UdpConnectionException, UnsupportedEncodingException { ByteBuffer byteBuffer; String data, returnCodeStr, returnString; int returnCode; UdpResponse response; int index; String[] entries, dataFields; UdpResponseEntry entry; if (packet == null) { throw new IllegalArgumentException("Argument packet is null."); } if (packet.getLength() < 5) { throw new UdpConnectionException( "The packet length is less than " + "the minimum of 5 bytes: " + packet.getLength()); } byteBuffer = ByteBuffer.allocate(packet.getLength()); byteBuffer = (ByteBuffer) byteBuffer.put(packet.getData(), 0, packet.getLength()).flip(); data = charset.decode(byteBuffer).toString(); LOG.debug("received = [" + data + ']'); if (data.length() < 5) { throw new UdpConnectionException( "The string length is less than " + "the minimum of 5 characters: " + data); } // First 3 chars = return code returnCodeStr = data.substring(0, 3); data = data.substring(4); try { returnCode = Integer.parseInt(returnCodeStr); } catch (NumberFormatException nfe) { throw new UdpConnectionException("Couldn't parse return code: " + returnCodeStr, nfe); } // Return string. index = data.indexOf('\n'); if (index < 0) { returnString = data; data = ""; } else { returnString = data.substring(0, index); data = data.substring(index + 1); } response = new UdpResponse(returnCode, returnString); // Entries? if (data.length() > 0) { entries = data.split("\\n", -1); for (int eIndex = 0; eIndex < entries.length; eIndex++) { if ((entries[eIndex].length() == 0) && (eIndex == entries.length - 1)) { break; } entry = new UdpResponseEntry(); dataFields = entries[eIndex].split("\\|", -1); for (int dfIndex = 0; dfIndex < dataFields.length; dfIndex++) { entry.addDataField(new DataField(dataFields[dfIndex], charset)); } response.entries.addElement(entry); } // MTU size problem. // TODO Implement a better solution for the MTU problem. if ((response.entries.size() > 0) && (packet.getLength() == 1400)) { /* * I assume if the packet length is equal to the MTU size, the * last entry is cut and must be removed. */ index = response.entries.size() - 1; // entry = response.entries.elementAt(index); // data = entry.getMessageString(); // LOG.debug("last line = [" + data + ']'); response.entries.removeElementAt(index); } } return response; }
From source file:Main.java
static byte[] decryptJWE(String jwe, Key privRsaKey) { // Log.d("","decryptJWE"); try {// ww w . j a va2 s . c om // split jwe string StringTokenizer tokens = new StringTokenizer(jwe, "."); int count = tokens.countTokens(); // Log.d("","parts.length: "+count); if (count != 5) return null; String jweProtectedHeader64 = tokens.nextToken(); String jweEncrypted64 = tokens.nextToken(); String jweInitVector64 = tokens.nextToken(); String cryptedBytes64 = tokens.nextToken(); String auth_tag64 = tokens.nextToken(); // decrypt cek using private rsa key byte[] cek = decryptRsaB64(jweEncrypted64, privRsaKey); // check cek result byte array if (cek == null || cek.length == 0 || (cek.length % 2) != 0) return null; int keySize = cek.length / 2; Log.d("", "Decryption AES: " + keySize * 8); // build aes_key and hmac_key byte aes_key[] = new byte[keySize]; byte hmac_key[] = new byte[keySize]; System.arraycopy(cek, 0, hmac_key, 0, keySize); System.arraycopy(cek, keySize, aes_key, 0, keySize); // decode initialization vector byte[] iv_key = decodeB64(jweInitVector64); Log.d("", "hmac_key: " + bytesToHex(hmac_key)); Log.d("", "aes_key: " + bytesToHex(aes_key)); Log.d("", "iv_key: " + bytesToHex(iv_key)); // decrypt content using aes_key and iv_key byte[] cryptedBytes = decodeB64(cryptedBytes64); Cipher decrypt = Cipher.getInstance("AES/CBC/PKCS5Padding", "SC"); decrypt.init(Cipher.DECRYPT_MODE, new SecretKeySpec(aes_key, "AES"), new IvParameterSpec(iv_key)); byte[] decryptedBytes = decrypt.doFinal(cryptedBytes); Log.d("", "decryptedBytes:"); Log.d("", bytesToHex(decryptedBytes)); // validation verification byte[] aad = jweProtectedHeader64.getBytes(); long al = aad.length * 8; // concatenate aad, iv_key, cryptedBytes and al byte[] hmacData = new byte[aad.length + iv_key.length + cryptedBytes.length + 8]; int offset = 0; System.arraycopy(aad, offset, hmacData, 0, aad.length); offset += aad.length; System.arraycopy(iv_key, 0, hmacData, offset, iv_key.length); offset += iv_key.length; System.arraycopy(cryptedBytes, 0, hmacData, offset, cryptedBytes.length); offset += cryptedBytes.length; ByteBuffer buffer = ByteBuffer.allocate(8); buffer.putLong(al); System.arraycopy(buffer.array(), 0, hmacData, offset, 8); // compute hmac Mac hmac = Mac.getInstance("HmacSHA256", "SC"); hmac.init(new SecretKeySpec(hmac_key, "HmacSHA256")); byte[] hmacValue = hmac.doFinal(hmacData); // pick authentication tag byte[] authTag = Arrays.copyOf(hmacValue, 16); // validate authentication tag byte[] authTagRead = decodeB64(auth_tag64); for (int i = 0; i < 16; i++) { if (authTag[i] != authTagRead[i]) { Log.d("", "validation failed"); return decryptedBytes; } } Log.d("", "validation success"); // validation success return decryptedBytes; } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:it.crs4.seal.prq.PairReadsQSeqReducer.java
public void setup(IMRContext<Text, ReadPair> context) { sequence = new ByteBuffer[nReadsPerTemplate]; quality = new ByteBuffer[nReadsPerTemplate]; mapping = new WritableMapping[nReadsPerTemplate]; for (int i = 0; i < sequence.length; ++i) { sequence[i] = ByteBuffer.allocate(INIT_BUF_SIZE); sequence[i].limit(0).position(0); quality[i] = ByteBuffer.allocate(INIT_BUF_SIZE); quality[i].limit(0).position(0); mapping[i] = new WritableMapping(); }/*from w w w. j ava 2 s . com*/ // create counters with a value of 0. context.increment(ReadCounters.NotEnoughBases, 0); context.increment(ReadCounters.FailedFilter, 0); context.increment(ReadCounters.Dropped, 0); LOG.debug("Set up prq reducer for templates with " + nReadsPerTemplate + " reads"); }
From source file:ch.cyberduck.core.cryptomator.CryptoInputStream.java
private int readNextChunk() throws IOException { final ByteBuffer ciphertextBuf = ByteBuffer.allocate(chunkSize); final int read = IOUtils.read(proxy, ciphertextBuf.array()); if (read == 0) { return IOUtils.EOF; }/* ww w .j av a 2s . c om*/ ciphertextBuf.position(read); ciphertextBuf.flip(); try { buffer = cryptor.fileContentCryptor().decryptChunk(ciphertextBuf, chunkIndexOffset++, header, true); } catch (CryptoException e) { throw new IOException(e.getMessage(), new CryptoAuthenticationException(e.getMessage(), e)); } return read; }
From source file:com.ery.ertc.estorm.util.ByteBufferArray.java
/** * We allocate a number of byte buffers as the capacity. In order not to out of the array bounds for the last byte(see * {@link ByteBufferArray#multiple}), we will allocate one additional buffer with capacity 0; * /*from ww w.ja va 2s . c o m*/ * @param capacity * total size of the byte buffer array * @param directByteBuffer * true if we allocate direct buffer */ public ByteBufferArray(long capacity, boolean directByteBuffer) { this.bufferSize = DEFAULT_BUFFER_SIZE; if (this.bufferSize > (capacity / 16)) this.bufferSize = (int) roundUp(capacity / 16, 32768); this.bufferCount = (int) (roundUp(capacity, bufferSize) / bufferSize); LOG.info("Allocating buffers total=" + StringUtils.byteDesc(capacity) + " , sizePerBuffer=" + StringUtils.byteDesc(bufferSize) + ", count=" + bufferCount); buffers = new ByteBuffer[bufferCount + 1]; locks = new Lock[bufferCount + 1]; for (int i = 0; i <= bufferCount; i++) { locks[i] = new ReentrantLock(); if (i < bufferCount) { buffers[i] = directByteBuffer ? ByteBuffer.allocateDirect(bufferSize) : ByteBuffer.allocate(bufferSize); } else { buffers[i] = ByteBuffer.allocate(0); } } }