List of usage examples for java.nio ByteBuffer array
public final byte[] array()
From source file:edu.umn.cs.spatialHadoop.nasa.HDFRasterLayer.java
@Override public void write(DataOutput out) throws IOException { super.write(out); out.writeLong(timestamp);/*from w ww . j av a 2 s. c o m*/ ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream gzos = new GZIPOutputStream(baos); ByteBuffer bbuffer = ByteBuffer.allocate(getHeight() * 2 * 8 + 8); bbuffer.putInt(getWidth()); bbuffer.putInt(getHeight()); gzos.write(bbuffer.array(), 0, bbuffer.position()); for (int x = 0; x < getWidth(); x++) { bbuffer.clear(); for (int y = 0; y < getHeight(); y++) { bbuffer.putLong(sum[x][y]); bbuffer.putLong(count[x][y]); } gzos.write(bbuffer.array(), 0, bbuffer.position()); } gzos.close(); byte[] serializedData = baos.toByteArray(); out.writeInt(serializedData.length); out.write(serializedData); }
From source file:mobisocial.musubi.nearby.GpsBroadcastTask.java
@Override protected Void doInBackground(Void... params) { if (DBG)/*from ww w. ja va2s .c o m*/ 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:com.intel.hadoop.hbase.dot.doc.serializer.AvroData.java
byte[] getValue(String field) { Object value = this.record.get(field); if (null != value) { ByteBuffer buf = (ByteBuffer) value; // when reusing record, ByteBuffer size could be larger than actual data // need to check the limit and return byte[] only contain the real data. return buf.limit() == buf.capacity() ? buf.array() : Bytes.getBytes(buf); }// ww w . j a va2 s. c o m return null; }
From source file:au.org.ala.delta.io.BinaryKeyFile.java
public int writeToRecord(int recordNumber, List<Integer> values) { ByteBuffer bytes = ByteBuffer.allocate(values.size() * SIZE_INT_IN_BYTES); bytes.order(ByteOrder.LITTLE_ENDIAN); for (int value : values) { bytes.putInt(value);/* www .j ava2s . c o m*/ } return writeToRecord(recordNumber, 0, bytes.array()); }
From source file:au.org.ala.delta.io.BinaryKeyFile.java
public int writeFloatsToRecord(int recordNumber, List<Float> values) { ByteBuffer bytes = ByteBuffer.allocate(values.size() * SIZE_INT_IN_BYTES); bytes.order(ByteOrder.LITTLE_ENDIAN); for (float value : values) { bytes.putFloat(value);/*from ww w .j a va 2 s . com*/ } return writeToRecord(recordNumber, 0, bytes.array()); }
From source file:com.bitbreeds.webrtc.datachannel.DataChannelImpl.java
@Override public void run() { if (parent.getRemote() == null) { throw new IllegalArgumentException("No user data set for remote user"); }//from w ww . j a v a 2 s . c o m logger.info("Started listening to port: " + port); while (running && channel.isBound()) { byte[] bt = new byte[bufferSize]; try { if (mode == ConnectionMode.BINDING) { logger.info("Listening for binding on: " + channel.getLocalSocketAddress() + " - " + channel.getPort()); Thread.sleep(5); //No reason to hammer on this DatagramPacket packet = new DatagramPacket(bt, 0, bt.length); channel.receive(packet); SocketAddress currentSender = packet.getSocketAddress(); sender = currentSender; byte[] data = Arrays.copyOf(packet.getData(), packet.getLength()); logger.info("Received data: " + Hex.encodeHexString(data) + " on " + channel.getLocalSocketAddress() + " - " + channel.getPort()); byte[] out = bindingService.processBindingRequest(data, parent.getLocal().getUserName(), parent.getLocal().getPassword(), (InetSocketAddress) currentSender); ByteBuffer outData = ByteBuffer.wrap(out); logger.info("Sending: " + Hex.encodeHexString(outData.array()) + " to " + currentSender); DatagramPacket pc = new DatagramPacket(out, 0, out.length); pc.setSocketAddress(sender); channel.send(pc); this.mode = ConnectionMode.HANDSHAKE; //Go to handshake mode logger.info("-> DTLS handshake"); } else if (mode == ConnectionMode.HANDSHAKE) { Thread.sleep(5); logger.info("In handshake mode: "); if (transport == null) { channel.connect(sender); /** * {@link NioUdpTransport} might replace the {@link UDPTransport} here. * @see <a href="https://github.com/RestComm/mediaserver/blob/master/io/rtp/src/main/java/org/mobicents/media/server/impl/srtp/NioUdpTransport.java">NioUdpTransport</a> */ transport = serverProtocol.accept(dtlsServer, new DtlsMuxStunTransport(parent, channel, MTU)); } sctpService = new SCTPImpl(this); mode = ConnectionMode.TRANSFER; logger.info("-> SCTP mode"); } else if (mode == ConnectionMode.TRANSFER) { /** * Here we receive message and put them to a worker thread for handling * If the output of handling the message is a message, then we send those * using the same thread. */ byte[] buf = new byte[transport.getReceiveLimit()]; int length = transport.receive(buf, 0, buf.length, waitMillis); if (length >= 0) { byte[] handled = Arrays.copyOf(buf, length); workPool.submit(() -> { try { List<byte[]> data = sctpService.handleRequest(handled); data.forEach(this::putDataOnWire); } catch (Exception e) { logger.error("Failed handling message: ", e); } }); logger.debug("Input: " + Hex.encodeHexString(handled)); } } } catch (Exception e) { logger.error("Com error:", e); logger.info("Shutting down, we cannot continue here"); running = false; //Need to quit channel now } } workPool.shutdown(); }
From source file:com.github.cambierr.lorawanpacket.semtech.Txpk.java
public JSONObject toJson() throws MalformedPacketException { JSONObject output = new JSONObject(); output.put("imme", isImme()); output.put("tmst", getTmst()); output.put("time", getTime()); output.put("freq", getFreq()); output.put("rfch", getRfch()); output.put("powe", getPowe()); output.put("modu", getModu().name()); if (getModu().equals(Modulation.LORA)) { output.put("codr", getCodr()); output.put("ipol", isIpol()); } else {//from w ww . j a va 2 s . co m output.put("fdev", getFdev()); } output.put("datr", getDatr()); output.put("prea", getPrea()); output.put("size", getSize()); output.put("ncrc", isNcrc()); ByteBuffer bb = ByteBuffer.allocate(384); getData().toRaw(bb); output.put("data", Base64.getEncoder() .encodeToString(Arrays.copyOfRange(bb.array(), 0, bb.capacity() - bb.remaining()))); return output; }
From source file:au.org.ala.delta.io.BinaryKeyFile.java
/** * Designed to allow headers and index records to be overwritten. * //from w ww.j a va 2 s.c om * @param recordNumber * the first (of possibily many, depending on the number of * values) record to be overwritten. * @param values * the values to write, starting at record, recordNumber.. */ public void overwriteRecord(int recordNumber, List<Integer> values) { if (!_occupiedRecords.contains(recordNumber)) { throw new IllegalArgumentException("Record " + recordNumber + " has not been allocated."); } ByteBuffer bytes = ByteBuffer.allocate(values.size() * SIZE_INT_IN_BYTES); bytes.order(ByteOrder.LITTLE_ENDIAN); for (int value : values) { bytes.putInt(value); } seekToRecord(recordNumber, 0); write(bytes.array()); }
From source file:au.org.ala.delta.io.BinaryKeyFile.java
public int writeBooleansToRecord(int recordNumber, List<Boolean> values) { ByteBuffer bytes = ByteBuffer.allocate(values.size() * SIZE_INT_IN_BYTES); bytes.order(ByteOrder.LITTLE_ENDIAN); for (boolean value : values) { bytes.putInt(value ? 1 : 0);/*from w w w . j ava 2 s .co m*/ } return writeToRecord(recordNumber, 0, bytes.array()); }
From source file:com.act.lcms.v2.fullindex.Searcher.java
/** * Extracts the value bytes from the index corresponding to a list of keys of fixed primitive type. * @param cf The column family from which to read. * @param keys A list of keys whose values to extract. * @param keyBytes The exact number of bytes required by a key; should be uniform for primitive-typed keys * @param put A function that writes a key to a ByteBuffer. * @param <K> The type of the key. * @return An array of arrays of bytes, one per key, containing the values of the key at that position. * @throws RocksDBException/*from ww w.java2 s . c o m*/ */ private <K> byte[][] extractValueBytes(ColumnFamilies cf, List<K> keys, int keyBytes, BiFunction<ByteBuffer, K, ByteBuffer> put) throws RocksDBException { byte[][] valBytes = new byte[keys.size()][]; ByteBuffer keyBuffer = ByteBuffer.allocate(keyBytes); for (int i = 0; i < keys.size(); i++) { K k = keys.get(i); keyBuffer.clear(); put.apply(keyBuffer, k).flip(); // TODO: try compacting the keyBuffer array to be safe? valBytes[i] = dbAndHandles.get(cf, keyBuffer.array()); assert (valBytes[i] != null); } return valBytes; }