List of usage examples for java.nio ByteBuffer put
public ByteBuffer put(ByteBuffer src)
From source file:edu.umass.cs.reconfiguration.reconfigurationpackets.ReconfigurationPacket.java
@Override public byte[] toBytes() { byte[] body = null; try {//from ww w. j a va2s . c o m body = this.toString().getBytes(CHARSET); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } if (!BYTEIFICATION) return body; // else byte[] bytes = new byte[body.length + 4]; ByteBuffer bbuf = ByteBuffer.wrap(bytes); bbuf.putInt(this.getType().getInt()); bbuf.put(body); return bytes; }
From source file:com.unister.semweb.drums.file.EnlargeFileTest.java
/** * Writes the given test data to the test file. The <code>globalParameters</code> are used to control the increment * and the initial file size.//from w w w. ja va 2 s. co m */ private List<Long> writeData(List<TestStorable> toWrite, DRUMSParameterSet<TestStorable> globalParameters) throws Exception { HeaderIndexFile<TestStorable> file = new HeaderIndexFile<TestStorable>(testFilename, AccessMode.READ_WRITE, 1, globalParameters); List<Long> filePositions = new ArrayList<Long>(); ByteBuffer overallBuffer = ByteBuffer.allocate(globalParameters.getPrototype().getSize() * toWrite.size()); long currentFilePosition = file.getFilledUpFromContentStart(); for (TestStorable currentTestObject : toWrite) { ByteBuffer buffer = currentTestObject.toByteBuffer(); overallBuffer.put(buffer); filePositions.add(currentFilePosition); currentFilePosition += globalParameters.getPrototype().getSize(); } overallBuffer.flip(); file.append(overallBuffer); file.close(); return filePositions; }
From source file:Base64Encoder.java
/** * Flushes this encoder./*from www .j av a 2 s . c o m*/ * * <p> The default implementation of this method does nothing, and always * returns {@link CoderResult#UNDERFLOW}. This method should be overridden * by encoders that may need to write final bytes to the output buffer * once the entire input sequence has been read. </p> * * @param out * The output byte buffer * * @return A coder-result object, either {@link CoderResult#UNDERFLOW} or * {@link CoderResult#OVERFLOW} */ protected java.nio.charset.CoderResult implFlush(java.nio.ByteBuffer out) { if (encState != 0 && encState != 4) throw new IllegalArgumentException("Base-64 text ends prematurely"); if (excessByte == null) { implReset(); return CoderResult.UNDERFLOW; } if (out.remaining() > 0) { out.put(excessByte.byteValue()); implReset(); return CoderResult.UNDERFLOW; } else return CoderResult.OVERFLOW; }
From source file:gridool.memcached.gateway.MemcachedProxyHandler.java
@Override public byte[] handleGet(byte[] key) { final ByteBuffer reqPacket = ByteBuffer.allocate(HEADER_LENGTH + key.length); // request header Header header = new Header(MAGIC_BYTE_REQUEST, OPCODE_GET); header.setBodyLength(GET_EXTRA_LENGTH, key.length, 0); header.encode(reqPacket);/*from w ww . j a v a 2 s.c o m*/ // request body (key) reqPacket.put(key); reqPacket.flip(); final byte[] value; final SocketAddress sockAddr = getSocket(key); final ByteChannel channel = sockPool.borrowObject(sockAddr); try { // handle request NIOUtils.writeFully(channel, reqPacket); // handle response header ByteBuffer responseHeaderPacket = ByteBuffer.allocate(HEADER_LENGTH); NIOUtils.readFully(channel, responseHeaderPacket); responseHeaderPacket.flip(); // handle response body int totalBody = responseHeaderPacket.getInt(8); int keyLen = responseHeaderPacket.getShort(2); int extraLen = responseHeaderPacket.get(4); int bodyPos = extraLen + keyLen; int bodyLen = totalBody - bodyPos; if (bodyLen <= 0) { return null; } ByteBuffer responseBodyPacket = ByteBuffer.allocate(totalBody); NIOUtils.readFully(channel, responseBodyPacket); responseBodyPacket.flip(); value = new byte[bodyLen]; responseBodyPacket.get(value, 0, bodyLen); } catch (IOException e) { LOG.error(e); return null; } finally { sockPool.returnObject(sockAddr, channel); } return value; }
From source file:mobisocial.musubi.nearby.GpsBroadcastTask.java
@Override protected Void doInBackground(Void... params) { if (DBG)/* w ww .j a va 2 s .c om*/ Log.d(TAG, "Uploading group for nearby gps..."); while (!mmLocationScanComplete) { synchronized (mmLocationResult) { if (!mmLocationScanComplete) { try { if (DBG) Log.d(TAG, "Waiting for location results..."); mmLocationResult.wait(); } catch (InterruptedException e) { } } } } if (DBG) Log.d(TAG, "Got location " + mmLocation); if (isCancelled()) { return null; } try { SQLiteOpenHelper db = App.getDatabaseSource(mContext); FeedManager fm = new FeedManager(db); IdentitiesManager im = new IdentitiesManager(db); String group_name = UiUtil.getFeedNameFromMembersList(fm, mFeed); byte[] group_capability = mFeed.capability_; List<MIdentity> owned = im.getOwnedIdentities(); MIdentity sharer = null; for (MIdentity i : owned) { if (i.type_ != Authority.Local) { sharer = i; break; } } String sharer_name = UiUtil.safeNameForIdentity(sharer); byte[] sharer_hash = sharer.principalHash_; byte[] thumbnail = fm.getFeedThumbnailForId(mFeed.id_); if (thumbnail == null) thumbnail = im.getMusubiThumbnail(sharer) != null ? sharer.musubiThumbnail_ : im.getThumbnail(sharer); int member_count = fm.getFeedMemberCount(mFeed.id_); JSONObject group = new JSONObject(); group.put("group_name", group_name); group.put("group_capability", Base64.encodeToString(group_capability, Base64.DEFAULT)); group.put("sharer_name", sharer_name); group.put("sharer_type", sharer.type_.ordinal()); group.put("sharer_hash", Base64.encodeToString(sharer_hash, Base64.DEFAULT)); if (thumbnail != null) group.put("thumbnail", Base64.encodeToString(thumbnail, Base64.DEFAULT)); group.put("member_count", member_count); byte[] key = Util.sha256(("happysalt621" + mmPassword).getBytes()); byte[] data = group.toString().getBytes(); byte[] iv = new byte[16]; new SecureRandom().nextBytes(iv); byte[] partial_enc_data; Cipher cipher; AlgorithmParameterSpec iv_spec; SecretKeySpec sks; try { cipher = Cipher.getInstance("AES/CBC/PKCS7Padding"); } catch (Exception e) { throw new RuntimeException("AES not supported on this platform", e); } try { iv_spec = new IvParameterSpec(iv); sks = new SecretKeySpec(key, "AES"); cipher.init(Cipher.ENCRYPT_MODE, sks, iv_spec); } catch (Exception e) { throw new RuntimeException("bad iv or key", e); } try { partial_enc_data = cipher.doFinal(data); } catch (Exception e) { throw new RuntimeException("body encryption failed", e); } TByteArrayList bal = new TByteArrayList(iv.length + partial_enc_data.length); bal.add(iv); bal.add(partial_enc_data); byte[] enc_data = bal.toArray(); if (DBG) Log.d(TAG, "Posting to gps server..."); Uri uri = Uri.parse("http://bumblebee.musubi.us:6253/nearbyapi/0/sharegroup"); StringBuffer sb = new StringBuffer(); DefaultHttpClient client = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(uri.toString()); httpPost.addHeader("Content-Type", "application/json"); JSONArray buckets = new JSONArray(); JSONObject descriptor = new JSONObject(); double lat = mmLocation.getLatitude(); double lng = mmLocation.getLongitude(); long[] coords = GridHandler.getGridCoords(lat, lng, 5280 / 2); for (long c : coords) { MessageDigest md; try { byte[] obfuscate = ("sadsalt193s" + mmPassword).getBytes(); md = MessageDigest.getInstance("SHA-256"); ByteBuffer b = ByteBuffer.allocate(8 + obfuscate.length); b.putLong(c); b.put(obfuscate); String secret_bucket = Base64.encodeToString(md.digest(b.array()), Base64.DEFAULT); buckets.put(buckets.length(), secret_bucket); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("your platform does not support sha256", e); } } descriptor.put("buckets", buckets); descriptor.put("data", Base64.encodeToString(enc_data, Base64.DEFAULT)); descriptor.put("expiration", new Date().getTime() + 1000 * 60 * 60); httpPost.setEntity(new StringEntity(descriptor.toString())); try { HttpResponse execute = client.execute(httpPost); InputStream content = execute.getEntity().getContent(); BufferedReader buffer = new BufferedReader(new InputStreamReader(content)); String s = ""; while ((s = buffer.readLine()) != null) { if (isCancelled()) { return null; } sb.append(s); } if (sb.toString().equals("ok")) mSucceeded = true; else { System.err.println(sb); } } catch (Exception e) { e.printStackTrace(); } //TODO: report failures etc } catch (Exception e) { Log.e(TAG, "Failed to broadcast group", e); } return null; }
From source file:MainClass.java
public void run() { try {/* ww w .j a va2s . c o m*/ ByteBuffer buffer = ByteBuffer.allocate(4); buffer.putInt(this.howMany); buffer.flip(); while (buffer.hasRemaining()) out.write(buffer); for (int i = 0; i < howMany; i++) { byte[] data = new BigInteger(Integer.toString(i)).toByteArray(); buffer = ByteBuffer.allocate(4 + data.length); buffer.putInt(data.length); buffer.put(data); buffer.flip(); while (buffer.hasRemaining()) out.write(buffer); } out.close(); System.err.println("Closed"); } catch (IOException ex) { System.err.println(ex); } }
From source file:net.dv8tion.jda.audio.AudioWebSocket.java
private void setupUdpKeepAliveThread() { udpKeepAliveThread = new Thread("AudioWebSocket UDP-KeepAlive Guild: " + guild.getId()) { @Override/* w w w . ja v a 2s .c o m*/ public void run() { while (socket.isOpen() && !udpSocket.isClosed() && !this.isInterrupted()) { long seq = 0; try { ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES + 1); buffer.put((byte) 0xC9); buffer.putLong(seq); DatagramPacket keepAlivePacket = new DatagramPacket(buffer.array(), buffer.array().length, address); udpSocket.send(keepAlivePacket); Thread.sleep(5000); //Wait 5 seconds to send next 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(true, -1); break; } catch (IOException e) { LOG.log(e); } catch (InterruptedException e) { //We were asked to close. // e.printStackTrace(); } } } }; udpKeepAliveThread.setPriority(Thread.NORM_PRIORITY + 1); udpKeepAliveThread.setDaemon(true); udpKeepAliveThread.start(); }
From source file:com.google.gdocsfs.GoogleDocsFS.java
public int getxattr(String path, String name, ByteBuffer dst) { Document document = getDocument(path); if (document == null) { return Errno.ENOENT; }//w w w . ja v a 2 s . c om if (ATTR_MIMETYPE.equals(name)) { dst.put(document.getMimetype().getBytes()); return 0; } return Errno.ENOATTR; }
From source file:com.neovisionaries.security.DigestTest.java
@Test public void test10() { ByteBuffer byteBuffer = ByteBuffer.allocate(10); byteBuffer.put(new byte[] { 1, 2, 3, 4, 5 }); byteBuffer.flip();//from w w w .j ava2 s. co m // Ensure there is no infinite loop. Digest.getInstanceSHA256().update("Hello, world.", new String[] { "Hello", "world" }, Boolean.TRUE, new boolean[] { true, false }, new Boolean[] { Boolean.TRUE, Boolean.FALSE }, Byte.valueOf((byte) 0), new byte[] { (byte) 0, (byte) 1 }, new Byte[] { Byte.valueOf((byte) 0), Byte.valueOf((byte) 1) }, byteBuffer, Character.valueOf('b'), new char[] { 'a', 'b' }, new Character[] { Character.valueOf('a'), Character.valueOf('b') }, Double.valueOf(0.0), new double[] { 0.0, 1.0 }, new Double[] { Double.valueOf(0.0), Double.valueOf(1.0) }, Float.valueOf(0.0F), new float[] { 0.0F, 1.0F }, new Float[] { Float.valueOf(0.0F), Float.valueOf(1.0F) }, Integer.valueOf(1), new int[] { 1, 2 }, new Integer[] { Integer.valueOf(0), Integer.valueOf(1) }, Long.valueOf(0L), new long[] { 0L, 1L }, new Long[] { Long.valueOf(0L), Long.valueOf(1L) }, Short.valueOf((short) 0), new short[] { (short) 0, (short) 1 }, new Short[] { Short.valueOf((short) 0), Short.valueOf((short) 1) }, new Object[] { new boolean[] { true, false }, new byte[] { (byte) 0, (byte) 1 } }, new Object[] { new Object[] { new char[] { 'a', 'b' }, new short[] { 10, 20 } }, new Object[] { new float[] { 1.0F, 2.0F }, new double[] { 3.0, 4.0 } } }); assertTrue(true); }
From source file:it.geosolutions.opensdi2.service.impl.FileUploadServiceImpl.java
/** * Create a temporal file with a byte array * // w ww . ja va2 s . co m * @param key of the file * @param bytes to write * @param i index by the file name * @return absolute path to the file * @throws IOException */ public String createTemporalFile(String key, byte[] bytes, int i) throws IOException { String filePath = temporaryFolder + File.separator + key; try { // write bytes File tmpFile = new File(filePath); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Appending bytes to " + tmpFile.getAbsolutePath()); } // File channel to append bytes @SuppressWarnings("resource") FileChannel channel = new FileOutputStream(tmpFile, true).getChannel(); ByteBuffer buf = ByteBuffer.allocateDirect((int) bytes.length); // put bytes buf.put(bytes); // Flips this buffer. The limit is set to the current position and then // the position is set to zero. If the mark is defined then it is discarded. buf.flip(); // Writes a sequence of bytes to this channel from the given buffer. channel.write(buf); // close the channel channel.close(); } catch (IOException e) { LOGGER.error("Error writing file bytes", e); } return filePath; }